My images do not appear in my UIImageView when i am in event, in my viewDidLoad no problem.
(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if ( event.subtype == UIEventSubtypeMotionShake )
{
int i;
int r;
for ( i = 1 ; i <= 5 ; )
{
r = (arc4random()%NbrCells) + 1;
if (GridCell[r].hidden == NO)
{
// View position.
CGFloat OriginX = GridCell[r].frame.origin.x;
CGFloat OriginY = GridCell[r].frame.origin.y;
CGFloat Height = GridCell[r].frame.size.height;
CGFloat Whidth = GridCell[r].frame.size.width;
[GridCell[r] removeFromSuperview];
GridCell[r] = nil;
GridCell[r] = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"background.png"]];
GridCell[r].frame = CGRectMake(OriginX, OriginY, Whidth, Height);
GridCell[r].hidden = NO;
[self.MyImage1 addSubview:GridCell[r]];
// [MyArray[r] addObject:[NSNumber numberWithInt:NO]];
i++;
sleep(1);
}
}
NSLog(#"Event stop, number delete = %d", i - 1);
}
if ( [super respondsToSelector:#selector(motionEnded:withEvent:)] )
[super motionEnded:motion withEvent:event];
return;
}
Many Thanks.
Alan10977.
Related
in an UIRotationGestureRecognizer i will do an action drawCircleView.
But this action should start max 10 times in a second.
UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:#selector(rotateContainerView:)];
rotation.delegate = self;
[_containerView addGestureRecognizer:rotation];
- (void)rotateContainerView:(UIRotationGestureRecognizer*)sender
{
static CGFloat initialScale;
if (sender.state == UIGestureRecognizerStateBegan) {
initialScale = (_Ro + 0.1)*-1;
_Rotation=0;
}
_Ro = (sender.rotation*-1);
sleep(.1);
[self drawCircleView];
}
I have test the following
sleep(0.1);
[NSThread sleepForTimeInterval:.1];
NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow:0.1]];
[NSThread sleepForTimeInterval:.1];
But with all it seems that all the action goes in a queue.
How i can do this without a query queue?
Full code
//
// CLHoleEffect.m
//
// Created by Kevin Siml - Appzer.de on 2013/10/23.
// Copyright (c) 2013 Appzer.de. All rights reserved.
//
#import "CLSwirlEffect.h"
#import "UIView+Frame.h"
#interface CLSwirlCircle : UIView
#property (nonatomic, strong) UIColor *color;
#end
#interface CLSwirlEffect()
<UIGestureRecognizerDelegate>
#end
#implementation CLSwirlEffect
{
UIView *_containerView;
UIView *_container;
CLSwirlCircle *_circleView;
UILabel* circleLabel;
CGFloat _X;
CGFloat _Y;
CGFloat _R;
CGFloat _Ro;
CGFloat _Rotation;
}
#pragma mark-
+ (NSString*)defaultTitle
{
return NSLocalizedStringWithDefaultValue(#"CLSwirlEffect_DefaultTitle", nil, [CLImageEditorTheme bundle], #"Swirl", #"");
}
+ (BOOL)isAvailable
{
return ([UIDevice iosVersion] >= 5.0);
}
- (id)initWithSuperView:(UIView*)superview imageViewFrame:(CGRect)frame toolInfo:(CLImageToolInfo *)info
{
self = [super initWithSuperView:superview imageViewFrame:frame toolInfo:info];
if(self){
_containerView = [[UIView alloc] initWithFrame:frame];
[superview addSubview:_containerView];
_X = 0.5;
_Y = 0.5;
_R = 0.5;
_Ro = 0.5;
[self setUserInterface];
}
return self;
}
- (void)cleanup
{
[_containerView removeFromSuperview];
}
- (UIImage*)applyEffect:(UIImage*)image
{
CGFloat R = (_R + 0.1);
GPUImageSwirlFilter *stillImageFilter = [[GPUImageSwirlFilter alloc] init];
[stillImageFilter setAngle: _Ro];
[stillImageFilter setRadius:R];
[stillImageFilter setCenter:CGPointMake(_X,_Y)];
UIImage *quickFilteredImage = [stillImageFilter imageByFilteringImage:image];
return quickFilteredImage;
}
#pragma mark-
- (void)setUserInterface
{
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapContainerView:)];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(panContainerView:)];
UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(pinchContainerView:)];
UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:#selector(rotateContainerView:)];
pan.maximumNumberOfTouches = 1;
tap.delegate = self;
pan.delegate = self;
pinch.delegate = self;
rotation.delegate = self;
[_containerView addGestureRecognizer:tap];
[_containerView addGestureRecognizer:pan];
[_containerView addGestureRecognizer:pinch];
[_containerView addGestureRecognizer:rotation];
_circleView = [[CLSwirlCircle alloc] init];
_circleView.backgroundColor = [UIColor clearColor];
_circleView.color = [UIColor whiteColor];
[_containerView addSubview:_circleView];
[self drawCircleView];
}
#define DEGREES_TO_RADIANS(x) (M_PI * x / 180.0)
- (void)drawCircleView
{
CGFloat R = MIN(_containerView.width, _containerView.height) * (_R + 0.1) * 1.2;
_circleView.width = R;
_circleView.height = R;
_circleView.center = CGPointMake(_containerView.width * _X, _containerView.height * _Y);
[_circleView setNeedsDisplay];
[self.delegate effectParameterDidChange:self];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
// if the gesture recognizers are on different views, don't allow simultaneous recognition
if (gestureRecognizer.view != otherGestureRecognizer.view)
return NO;
// if either of the gesture recognizers is the long press, don't allow simultaneous recognition
if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]] || [otherGestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
return NO;
return YES;
}
- (void)tapContainerView:(UITapGestureRecognizer*)sender
{
CGPoint point = [sender locationInView:_containerView];
_X = MIN(1.0, MAX(0.0, point.x / _containerView.width));
_Y = MIN(1.0, MAX(0.0, point.y / _containerView.height));
[self drawCircleView];
if (sender.state == UIGestureRecognizerStateEnded){
[self.delegate effectParameterDidChange:self];
}
}
- (void)panContainerView:(UIPanGestureRecognizer*)sender
{
CGPoint point = [sender locationInView:_containerView];
_X = MIN(1.0, MAX(0.0, point.x / _containerView.width));
_Y = MIN(1.0, MAX(0.0, point.y / _containerView.height));
[self drawCircleView];
if (sender.state == UIGestureRecognizerStateEnded){
//[self.delegate effectParameterDidChange:self];
}
}
- (void)pinchContainerView:(UIPinchGestureRecognizer*)sender
{
static CGFloat initialScale;
if (sender.state == UIGestureRecognizerStateBegan) {
initialScale = (_R + 0.1);
}
_R = MIN(1.1, MAX(0.1, initialScale * sender.scale)) - 0.1;
[self drawCircleView];
if (sender.state == UIGestureRecognizerStateEnded){
// [self.delegate effectParameterDidChange:self];
}
}
- (void)rotateContainerView:(UIRotationGestureRecognizer*)sender
{
static CGFloat initialScale;
if (sender.state == UIGestureRecognizerStateBegan) {
initialScale = (_Ro + 0.1)*-1;
_Rotation=0;
}
_Ro = (sender.rotation*-1);
[self drawCircleView];
if (sender.state == UIGestureRecognizerStateEnded){
// [self.delegate effectParameterDidChange:self];
}
}
#end
#pragma mark- UI components
#implementation CLSwirlCircle
- (void)setFrame:(CGRect)frame
{
[super setFrame:frame];
[self setNeedsDisplay];
}
- (void)setCenter:(CGPoint)center
{
[super setCenter:center];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rct = self.bounds;
rct.origin.x += 1;
rct.origin.y += 1;
rct.size.width -= 2;
rct.size.height -= 2;
CGContextSetStrokeColorWithColor(context, self.color.CGColor);
CGContextStrokeEllipseInRect(context, rct);
self.alpha = 1;
[UIView animateWithDuration:kCLEffectToolAnimationDuration
delay:1
options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction
animations:^{
self.alpha = 0;
}
completion:^(BOOL finished) {
}
];
}
#end
To restrict the method, rotateContainerView:, being called no more than ten times in a second you could timestamp the first call and compare each subsequent calls timestamp, allowing the method to complete only if the calls timestamp is greater than last calls timestamp plus 0.1 seconds.
Add a property of type NSDate -
#property (nonatomic, strong) NSDate *lastCall;
Then modify rotateContainerView: to something like this -
- (void)rotateContainerView:(UIRotationGestureRecognizer*)sender
{
static CGFloat initialScale;
NSDate *nowCall = [NSDate date];// timestamp
if (sender.state == UIGestureRecognizerStateBegan) {
lastCall = nowCall;
initialScale = (_Ro + 0.1)*-1;
_Rotation=0;
_Ro = (sender.rotation*-1);
[self drawCircleView];
}
else {
if ([nowCall timeIntervalSinceDate:lastCall] > 0.1) {
_Ro = (sender.rotation*-1);
[self drawCircleView];
lastCall = nowCall;
}
}
}
drawRect is what's actually drawing the view. Decouple your data changes and the drawing changes. Draw your circles from drawRect, but change the rotation from a data method that you call instead of your current calls to drawCircleView. If you need to update on intervals, use a NSTimer to schedule calls to a rotate method. But leave the drawing of the actual circles up to drawRect. That way, you have guaranteed rotations, but the drawing happens all the time (which I think is what you want).
Does that make sense?
Im trying to change the color of the unselected images in the tab bar, by default they are changed to gray, even if the image is another color.
I already search this, but the answers are only for iOS 6 or below.
This drove me mad just recently so I wrote my own class to handle it that works with every version of iOS I've tried it on ;) Its really easy to extend to do whatever you want it to do too!
GozTabBar.h:
#import <UIKit/UIKit.h>
#import "GozTabBarItem.h"
#protocol GozTabBarDelegate;
#interface GozTabBar : UIView
{
UITapGestureRecognizer* pTapGestureRecognizer;
}
#property UIColor* backgroundColour;
#property (unsafe_unretained, nonatomic) id < GozTabBarDelegate > delegate;
#end
#protocol GozTabBarDelegate < NSObject >
- (int) getNumberOfTabBarItemsForTabBar: (GozTabBar*) pTabBar;
- (GozTabBarItem*) getTabBarItemsAtIndex: (int) index ForTabBar: (GozTabBar*) pTabBar;
- (void) selectedItemAtIndex: (int) index ForTabBar: (GozTabBar*) pTabBar;
- (int) getSelectedItemIndexForTabBar: (GozTabBar*) pTabBar;
#end
GozTabBar.m
#import "GozTabBar.h"
#import "GozTabBarItem.h"
#implementation GozTabBar
#synthesize backgroundColour;
#synthesize delegate;
const int leftEdgeInset = 8;
const int rightEdgeInset = 8;
const int topEdgeInset = 8;
const int bottomEdgeInset = 8;
- (id)init
{
self = [super init];
if (self)
{
pTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget: self action: #selector( onTap: )];
[self addGestureRecognizer: pTapGestureRecognizer];
}
return self;
}
- (id) initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
pTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget: self action: #selector( onTap: )];
[self addGestureRecognizer: pTapGestureRecognizer];
}
return self;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
pTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget: self action: #selector( onTap: )];
[self addGestureRecognizer: pTapGestureRecognizer];
}
return self;
}
// Recognise a tap on the item (If it is on an item).
- (void)onTap: (UIGestureRecognizer *)gestureRecognizer
{
const int leftRightEdgeInset = leftEdgeInset + rightEdgeInset;
const int topBottomEdgeInset = topEdgeInset + bottomEdgeInset;
int numItems = 0;
if ( [self.delegate respondsToSelector: #selector( getNumberOfTabBarItemsForTabBar: )] )
{
numItems = [self.delegate getNumberOfTabBarItemsForTabBar: self];
}
if ( numItems > 0 )
{
int widthLessInset = (self.frame.size.width - leftRightEdgeInset);
int itemWidth = widthLessInset / numItems;
int heightLessInset = self.frame.size.height - topBottomEdgeInset;
int itemHeight = heightLessInset;
CGPoint tapPoint = [gestureRecognizer locationInView: self];
// Draw the custom items.
for( int i = 0; i < numItems; i++ )
{
CGRect tabBarItemRect = CGRectMake( leftEdgeInset + (itemWidth * i), 0, itemWidth, itemHeight );
if ( CGRectContainsPoint( tabBarItemRect, tapPoint ) )
{
if ( [self.delegate respondsToSelector: #selector(selectedItemAtIndex:ForTabBar:)] )
{
[self.delegate selectedItemAtIndex: i ForTabBar: self];
}
break;
}
}
}
}
- (void)drawRect:(CGRect)rect
{
const int leftRightEdgeInset = leftEdgeInset + rightEdgeInset;
const int topBottomEdgeInset = topEdgeInset + bottomEdgeInset;
CGContextRef ctx = UIGraphicsGetCurrentContext();
// Fill the background in the relevant colour.
CGContextSetFillColorWithColor( ctx, backgroundColour.CGColor );
CGContextFillRect( ctx, rect );
int numItems = 0;
if ( [self.delegate respondsToSelector: #selector( getNumberOfTabBarItemsForTabBar: )] )
{
numItems = [self.delegate getNumberOfTabBarItemsForTabBar: self];
}
if ( numItems > 0 )
{
int widthLessInset = (rect.size.width - leftRightEdgeInset);
int itemWidth = widthLessInset / numItems;
int heightLessInset = rect.size.height - topBottomEdgeInset;
int itemHeight = heightLessInset;
int selectedIndex = 0;
if ( [self.delegate respondsToSelector: #selector(getSelectedItemIndexForTabBar:)] )
{
selectedIndex = [self.delegate getSelectedItemIndexForTabBar: self];
}
// Draw the custom items.
for( int i = 0; i < numItems; i++ )
{
//GozTabBarItem* pItem = [self.items objectAtIndex: i];
GozTabBarItem* pItem = nil;
if ( [self.delegate respondsToSelector: #selector(getTabBarItemsAtIndex:ForTabBar:)] )
{
pItem = [self.delegate getTabBarItemsAtIndex: i ForTabBar: self];
}
if ( pItem != nil )
{
CGRect tabBarItemRect = CGRectMake( leftEdgeInset + (itemWidth * i), topEdgeInset, itemWidth, itemHeight );
CGPoint tabBarItemCenter = CGPointMake( tabBarItemRect.origin.x + (tabBarItemRect.size.width / 2), tabBarItemRect.origin.y + (tabBarItemRect.size.height / 2) );
UIImage* pDrawImage = nil;
if ( i == selectedIndex )
{
pDrawImage = pItem.selectedImage;
}
else
{
pDrawImage = pItem.unSelectedImage;
}
CGRect drawRect = CGRectMake( tabBarItemCenter.x - (pDrawImage.size.width / 2), tabBarItemCenter.y - (pDrawImage.size.height / 2), pDrawImage.size.width, pDrawImage.size.height );
[pDrawImage drawInRect: drawRect];
}
}
}
}
GozTabBarItem.h
#import <UIKit/UIKit.h>
#interface GozTabBarItem : NSObject
{
}
#property UIImage* selectedImage;
#property UIImage* unSelectedImage;
- (id) initWithSelectedImage: (UIImage*) selectedImage andUnselectedImage: (UIImage*) unSelectedImage;
#end
GozTabBarItem.m
#import "GozTabBarItem.h"
#implementation GozTabBarItem
#synthesize selectedImage;
#synthesize unSelectedImage;
- (id) initWithSelectedImage: (UIImage*) selectedImg andUnselectedImage: (UIImage*) unSelectedImg
{
self = [super init];
if (self)
{
self.selectedImage = selectedImg;
self.unSelectedImage = unSelectedImg;
}
return self;
}
#end
Hope that helps.
I don't know how to flip my uiview vertically , i have many views and i every view
there are some photos and their description, i want a flip view like a book but not
left to right it must be top to bottom or bottom to top,
i want to flip the whole page vertically like top to bottom or bottom to top,
how to do this kind of work in ios ?
i m seraching on google but thats not working i'm new in developement
So please kindly anyone can guide me properly how can i flip my views Please Please help me
out
Thanks in advance.
download the code from https://github.com/mtabini/AFKPageFlipper
and change the AFKPageFlipper.h and AFKPageFlipper.m file
//
// AFKPageFlipper.h
// AFKPageFlipper
//
// Created by Marco Tabini on 10-10-11.
// Copyright 2010 AFK Studio Partnership. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#class AFKPageFlipper;
#protocol AFKPageFlipperDataSource
- (NSInteger) numberOfPagesForPageFlipper:(AFKPageFlipper *) pageFlipper;
- (UIView *) viewForPage:(NSInteger) page inFlipper:(AFKPageFlipper *) pageFlipper;
#end
typedef enum {
AFKPageFlipperDirectionTop,
AFKPageFlipperDirectionBottom,
} AFKPageFlipperDirection;
#interface AFKPageFlipper : UIView {
NSObject <AFKPageFlipperDataSource> *dataSource;
NSInteger currentPage;
NSInteger numberOfPages;
UIView *currentView;
UIView *nextView;
CALayer *backgroundAnimationLayer;
CALayer *flipAnimationLayer;
AFKPageFlipperDirection flipDirection;
float startFlipAngle;
float endFlipAngle;
float currentAngle;
BOOL setNextViewOnCompletion;
BOOL animating;
BOOL disabled;
}
#property (nonatomic,retain) NSObject <AFKPageFlipperDataSource> *dataSource;
#property (nonatomic,assign) NSInteger currentPage;
#property (nonatomic, retain) UITapGestureRecognizer *tapRecognizer;
#property (nonatomic, retain) UIPanGestureRecognizer *panRecognizer;
#property (nonatomic,assign) BOOL disabled;
- (void) setCurrentPage:(NSInteger) value animated:(BOOL) animated;
#end
//
// AFKPageFlipper.m
// AFKPageFlipper
//
// Created by Marco Tabini on 10-10-12.
// Copyright 2010 AFK Studio Partnership. All rights reserved.
//
#import "AFKPageFlipper.h"
#pragma mark -
#pragma mark UIView helpers
#interface UIView(Extended)
- (UIImage *) imageByRenderingView;
#end
#implementation UIView(Extended)
- (UIImage *) imageByRenderingView {
CGFloat oldAlpha = self.alpha;
self.alpha = 1;
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.alpha = oldAlpha;
return resultingImage;
}
#end
#pragma mark -
#pragma mark Private interface
#interface AFKPageFlipper()
#property (nonatomic,assign) UIView *currentView;
#property (nonatomic,assign) UIView *nextView;
#end
#implementation AFKPageFlipper
#synthesize tapRecognizer = _tapRecognizer;
#synthesize panRecognizer = _panRecognizer;
#pragma mark -
#pragma mark Flip functionality
- (void) initFlip {
// Create screenshots of view
UIImage *currentImage = [self.currentView imageByRenderingView];
UIImage *newImage = [self.nextView imageByRenderingView];
// Hide existing views
self.currentView.alpha = 0;
self.nextView.alpha = 0;
// Create representational layers
CGRect rect = self.bounds;
rect.size.height /= 2;
backgroundAnimationLayer = [CALayer layer];
backgroundAnimationLayer.frame = self.bounds;
backgroundAnimationLayer.zPosition = -300000;
CALayer *topLayer = [CALayer layer];
topLayer.frame = rect;
topLayer.masksToBounds = YES;
topLayer.contentsGravity = kCAGravityBottom;
[backgroundAnimationLayer addSublayer:topLayer];
rect.origin.y = rect.size.height;
CALayer *bottomLayer = [CALayer layer];
bottomLayer.frame = rect;
bottomLayer.masksToBounds = YES;
bottomLayer.contentsGravity = kCAGravityTop;
[backgroundAnimationLayer addSublayer:bottomLayer];
if (flipDirection == AFKPageFlipperDirectionBottom) {
topLayer.contents = (id) [newImage CGImage];
bottomLayer.contents = (id) [currentImage CGImage];
} else {
topLayer.contents = (id) [currentImage CGImage];
bottomLayer.contents = (id) [newImage CGImage];
}
[self.layer addSublayer:backgroundAnimationLayer];
rect.origin.y = 0;
flipAnimationLayer = [CATransformLayer layer];
flipAnimationLayer.anchorPoint = CGPointMake(0.5, 1);
flipAnimationLayer.frame = rect;
[self.layer addSublayer:flipAnimationLayer];
CALayer *backLayer = [CALayer layer];
backLayer.frame = flipAnimationLayer.bounds;
backLayer.doubleSided = NO;
backLayer.masksToBounds = YES;
[flipAnimationLayer addSublayer:backLayer];
CALayer *frontLayer = [CALayer layer];
frontLayer.frame = flipAnimationLayer.bounds;
frontLayer.doubleSided = NO;
frontLayer.masksToBounds = YES;
frontLayer.transform = CATransform3DMakeRotation(M_PI, 1.0, 0.0, 0);
[flipAnimationLayer addSublayer:frontLayer];
if (flipDirection == AFKPageFlipperDirectionBottom) {
backLayer.contents = (id) [currentImage CGImage];
backLayer.contentsGravity = kCAGravityBottom;
frontLayer.contents = (id) [newImage CGImage];
frontLayer.contentsGravity = kCAGravityTop;
CATransform3D transform = CATransform3DMakeRotation(1.1/M_PI, 1.0, 0.0, 0.0);
transform.m34 = 1.0f / 2500.0f;
flipAnimationLayer.transform = transform;
currentAngle = startFlipAngle = 0;
endFlipAngle = M_PI;
} else {
//down
backLayer.contents = (id) [newImage CGImage];
backLayer.contentsGravity = kCAGravityBottom;
frontLayer.contents = (id) [currentImage CGImage];
frontLayer.contentsGravity = kCAGravityTop;
CATransform3D transform = CATransform3DMakeRotation(M_PI/1.1, 1.0, 0.0, 0.0);
transform.m34 = 1.0f / 2500.0f;
flipAnimationLayer.transform = transform;
currentAngle = startFlipAngle = M_PI;
endFlipAngle = 0;
}
}
- (void) cleanupFlip {
[backgroundAnimationLayer removeFromSuperlayer];
[flipAnimationLayer removeFromSuperlayer];
backgroundAnimationLayer = Nil;
flipAnimationLayer = Nil;
animating = NO;
if (setNextViewOnCompletion) {
[self.currentView removeFromSuperview];
self.currentView = self.nextView;
self.nextView = Nil;
} else {
[self.nextView removeFromSuperview];
self.nextView = Nil;
}
self.currentView.alpha = 1;
}
- (void) setFlipProgress:(float) progress setDelegate:(BOOL) setDelegate animate:(BOOL) animate {
if (animate) {
animating = YES;
}
float newAngle = startFlipAngle + progress * (endFlipAngle - startFlipAngle);
float duration = animate ? 0.5 * fabs((newAngle - currentAngle) / (endFlipAngle - startFlipAngle)) : 0;
currentAngle = newAngle;
CATransform3D endTransform = CATransform3DIdentity;
endTransform.m34 = 1.0f / 2500.0f;
endTransform = CATransform3DRotate(endTransform, newAngle, 1.0, 0.0, 0.0);
[flipAnimationLayer removeAllAnimations];
[CATransaction begin];
[CATransaction setAnimationDuration:duration];
flipAnimationLayer.transform = endTransform;
[CATransaction commit];
if (setDelegate) {
[self performSelector:#selector(cleanupFlip) withObject:Nil afterDelay:duration];
}
}
- (void) flipPage {
[self setFlipProgress:1.0 setDelegate:YES animate:YES];
}
#pragma mark -
#pragma mark Animation management
- (void)animationDidStop:(NSString *) animationID finished:(NSNumber *) finished context:(void *) context {
[self cleanupFlip];
}
#pragma mark -
#pragma mark Properties
#synthesize currentView;
- (void) setCurrentView:(UIView *) value {
if (currentView) {
[currentView release];
}
currentView = [value retain];
}
#synthesize nextView;
- (void) setNextView:(UIView *) value {
if (nextView) {
[nextView release];
}
nextView = [value retain];
}
#synthesize currentPage;
- (BOOL) doSetCurrentPage:(NSInteger) value {
if (value == currentPage) {
return FALSE;
}
flipDirection = value < currentPage ? AFKPageFlipperDirectionBottom : AFKPageFlipperDirectionTop;
currentPage = value;
self.nextView = [self.dataSource viewForPage:value inFlipper:self];
[self addSubview:self.nextView];
return TRUE;
}
- (void) setCurrentPage:(NSInteger) value {
if (![self doSetCurrentPage:value]) {
return;
}
setNextViewOnCompletion = YES;
animating = YES;
self.nextView.alpha = 0;
[UIView beginAnimations:#"" context:Nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(animationDidStop:finished:context:)];
self.nextView.alpha = 1;
[UIView commitAnimations];
}
- (void) setCurrentPage:(NSInteger) value animated:(BOOL) animated {
if (![self doSetCurrentPage:value]) {
return;
}
setNextViewOnCompletion = YES;
animating = YES;
if (animated) {
[self initFlip];
[self performSelector:#selector(flipPage) withObject:Nil afterDelay:0.091];
} else {
[self animationDidStop:Nil finished:[NSNumber numberWithBool:NO] context:Nil];
}
}
#synthesize dataSource;
- (void) setDataSource:(NSObject <AFKPageFlipperDataSource>*) value {
if (dataSource) {
[dataSource release];
}
dataSource = [value retain];
numberOfPages = [dataSource numberOfPagesForPageFlipper:self];
currentPage = 0;
self.currentPage = 1;
}
#synthesize disabled;
- (void) setDisabled:(BOOL) value {
disabled = value;
self.userInteractionEnabled = !value;
for (UIGestureRecognizer *recognizer in self.gestureRecognizers) {
recognizer.enabled = !value;
}
}
#pragma mark -
#pragma mark Touch management
- (void) tapped:(UITapGestureRecognizer *) recognizer {
if (animating || self.disabled) {
return;
}
if (recognizer.state == UIGestureRecognizerStateRecognized) {
NSInteger newPage;
if ([recognizer locationInView:self].y < (self.bounds.size.height - self.bounds.origin.y) / 2) {
newPage = MAX(1, self.currentPage - 1);
} else {
newPage = MIN(self.currentPage + 1, numberOfPages);
}
[self setCurrentPage:newPage animated:YES];
}
}
- (void) panned:(UIPanGestureRecognizer *) recognizer {
if (animating) {
return;
}
static BOOL hasFailed;
static BOOL initialized;
static NSInteger oldPage;
float translation = [recognizer translationInView:self].y;
float progress = translation / self.bounds.size.height;
if (flipDirection == AFKPageFlipperDirectionTop) {
progress = MIN(progress, 0);
} else {
progress = MAX(progress, 0);
}
switch (recognizer.state) {
case UIGestureRecognizerStateBegan:
hasFailed = FALSE;
initialized = FALSE;
animating = NO;
setNextViewOnCompletion = NO;
break;
case UIGestureRecognizerStateChanged:
if (hasFailed) {
return;
}
if (!initialized) {
oldPage = self.currentPage;
if (translation > 0) {
if (self.currentPage > 1) {
[self doSetCurrentPage:self.currentPage - 1];
} else {
hasFailed = TRUE;
return;
}
} else {
if (self.currentPage < numberOfPages) {
[self doSetCurrentPage:self.currentPage + 1];
} else {
hasFailed = TRUE;
return;
}
}
hasFailed = NO;
initialized = TRUE;
setNextViewOnCompletion = NO;
[self initFlip];
}
[self setFlipProgress:fabs(progress) setDelegate:NO animate:NO];
break;
case UIGestureRecognizerStateFailed:
[self setFlipProgress:0.0 setDelegate:YES animate:YES];
currentPage = oldPage;
break;
case UIGestureRecognizerStateRecognized:
if (hasFailed) {
[self setFlipProgress:0.0 setDelegate:YES animate:YES];
currentPage = oldPage;
return;
}
if (fabs((translation + [recognizer velocityInView:self].y / 4) / self.bounds.size.height) > 0.5) {
setNextViewOnCompletion = YES;
[self setFlipProgress:1.0 setDelegate:YES animate:YES];
} else {
[self setFlipProgress:0.0 setDelegate:YES animate:YES];
currentPage = oldPage;
}
break;
default:
break;
}
}
#pragma mark -
#pragma mark Frame management
- (void) setFrame:(CGRect) value {
super.frame = value;
numberOfPages = [dataSource numberOfPagesForPageFlipper:self];
if (self.currentPage > numberOfPages) {
self.currentPage = numberOfPages;
}
}
#pragma mark -
#pragma mark Initialization and memory management
+ (Class) layerClass {
return [CATransformLayer class];
}
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
_tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapped:)];
_panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(panned:)];
[_tapRecognizer requireGestureRecognizerToFail:_panRecognizer];
[self addGestureRecognizer:_tapRecognizer];
[self addGestureRecognizer:_panRecognizer];
}
return self;
}
- (void)dealloc {
self.dataSource = Nil;
self.currentView = Nil;
self.nextView = Nil;
self.tapRecognizer = Nil;
self.panRecognizer = Nil;
[super dealloc];
}
#end
becoz of AFKPageFlipper, i am able to do the above code....credit goes to Mr. mtabini ( AFKPageFlipper author )
You could set a negative scale, like:
[theView setTransform:CGAffineTransformMakeScale(1, -1)];
Same as Pradeep, but with shadows, also ARC adapted:
AFKPageFlipper.h
//
// AFKPageFlipper.h
// AFKPageFlipper
//
// Created by Marco Tabini on 10-10-11.
// Copyright 2010 AFK Studio Partnership. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#class AFKPageFlipper;
#protocol AFKPageFlipperDataSource
- (NSInteger) numberOfPagesForPageFlipper:(AFKPageFlipper *) pageFlipper;
- (UIView *) viewForPage:(NSInteger) page inFlipper:(AFKPageFlipper *) pageFlipper;
#end
typedef enum {
AFKPageFlipperDirectionTop,
AFKPageFlipperDirectionBottom,
} AFKPageFlipperDirection;
#interface AFKPageFlipper : UIView {
NSObject <AFKPageFlipperDataSource> *dataSource;
NSInteger currentPage;
NSInteger numberOfPages;
// shadows
CALayer *frontLayerShadow;
CALayer *backLayerShadow;
CALayer *leftLayerShadow;
CALayer *rightLayerShadow;
// shadows
CALayer *backgroundAnimationLayer;
CALayer *flipAnimationLayer;
AFKPageFlipperDirection flipDirection;
float startFlipAngle;
float endFlipAngle;
float currentAngle;
BOOL setNextViewOnCompletion;
BOOL animating;
BOOL disabled;
}
#property (nonatomic,retain) NSObject <AFKPageFlipperDataSource> *dataSource;
#property (nonatomic,assign) NSInteger currentPage;
#property (nonatomic, retain) UITapGestureRecognizer *tapRecognizer;
#property (nonatomic, retain) UIPanGestureRecognizer *panRecognizer;
#property (nonatomic,assign) BOOL disabled;
- (void) setCurrentPage:(NSInteger) value animated:(BOOL) animated;
#end
AFKPageFlipper.m
//
// AFKPageFlipper.m
// AFKPageFlipper
//
// Created by Marco Tabini on 10-10-12.
// Copyright 2010 AFK Studio Partnership. All rights reserved.
//
#import "AFKPageFlipper.h"
#pragma mark -
#pragma mark UIView helpers
#interface UIView(Extended)
- (UIImage *) imageByRenderingView;
#end
#implementation UIView(Extended)
- (UIImage *) imageByRenderingView {
CGFloat oldAlpha = self.alpha;
self.alpha = 1;
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.alpha = oldAlpha;
return resultingImage;
}
#end
#pragma mark -
#pragma mark Private interface
#interface AFKPageFlipper()
#property (nonatomic,retain) UIView *currentView;
#property (nonatomic,retain) UIView *nextView;
#end
#implementation AFKPageFlipper
#synthesize tapRecognizer = _tapRecognizer;
#synthesize panRecognizer = _panRecognizer;
#pragma mark -
#pragma mark Flip functionality
- (void) initFlip {
// Create screenshots of view
UIImage *currentImage = [self.currentView imageByRenderingView];
UIImage *newImage = [self.nextView imageByRenderingView];
// Hide existing views
self.currentView.alpha = 0;
self.nextView.alpha = 0;
// Create representational layers
CGRect rect = self.bounds;
rect.size.height /= 2;
backgroundAnimationLayer = [CALayer layer];
backgroundAnimationLayer.frame = self.bounds;
backgroundAnimationLayer.zPosition = -300000;
CALayer *topLayer = [CALayer layer];
topLayer.frame = rect;
topLayer.masksToBounds = YES;
topLayer.contentsGravity = kCAGravityBottom;
[backgroundAnimationLayer addSublayer:topLayer];
rect.origin.y = rect.size.height;
CALayer *bottomLayer = [CALayer layer];
bottomLayer.frame = rect;
bottomLayer.masksToBounds = YES;
bottomLayer.contentsGravity = kCAGravityTop;
[backgroundAnimationLayer addSublayer:bottomLayer];
if (flipDirection == AFKPageFlipperDirectionBottom) {
topLayer.contents = (id) [newImage CGImage];
bottomLayer.contents = (id) [currentImage CGImage];
} else {
topLayer.contents = (id) [currentImage CGImage];
bottomLayer.contents = (id) [newImage CGImage];
}
[self.layer addSublayer:backgroundAnimationLayer];
rect.origin.y = 0;
flipAnimationLayer = [CATransformLayer layer];
flipAnimationLayer.anchorPoint = CGPointMake(0.5, 1);
flipAnimationLayer.frame = rect;
[self.layer addSublayer:flipAnimationLayer];
CALayer *backLayer = [CALayer layer];
backLayer.frame = flipAnimationLayer.bounds;
backLayer.doubleSided = NO;
backLayer.masksToBounds = YES;
[flipAnimationLayer addSublayer:backLayer];
CALayer *frontLayer = [CALayer layer];
frontLayer.frame = flipAnimationLayer.bounds;
frontLayer.doubleSided = NO;
frontLayer.masksToBounds = YES;
frontLayer.transform = CATransform3DMakeRotation(M_PI, 1.0, 0, 0);
[flipAnimationLayer addSublayer:frontLayer];
// shadows
frontLayerShadow = [CALayer layer];
frontLayerShadow.frame = frontLayer.bounds;
frontLayerShadow.doubleSided = NO;
frontLayerShadow.masksToBounds = YES;
frontLayerShadow.opacity = 0;
frontLayerShadow.backgroundColor = [UIColor blackColor].CGColor;
[frontLayer addSublayer:frontLayerShadow];
backLayerShadow = [CALayer layer];
backLayerShadow.frame = backLayer.bounds;
backLayerShadow.doubleSided = NO;
backLayerShadow.masksToBounds = YES;
backLayerShadow.opacity = 0;
backLayerShadow.backgroundColor = [UIColor blackColor].CGColor;
[backLayer addSublayer:backLayerShadow];
leftLayerShadow = [CALayer layer];
leftLayerShadow.frame = topLayer.bounds;
leftLayerShadow.doubleSided = NO;
leftLayerShadow.masksToBounds = YES;
leftLayerShadow.opacity = 0.0;
leftLayerShadow.backgroundColor = [UIColor blackColor].CGColor;
[topLayer addSublayer:leftLayerShadow];
rightLayerShadow = [CALayer layer];
rightLayerShadow.frame = bottomLayer.bounds;
rightLayerShadow.doubleSided = NO;
rightLayerShadow.masksToBounds = YES;
rightLayerShadow.opacity = 0.0;
rightLayerShadow.backgroundColor = [UIColor blackColor].CGColor;
[bottomLayer addSublayer:rightLayerShadow];
// shadows
if (flipDirection == AFKPageFlipperDirectionBottom) {
backLayer.contents = (id) [currentImage CGImage];
backLayer.contentsGravity = kCAGravityBottom;
frontLayer.contents = (id) [newImage CGImage];
frontLayer.contentsGravity = kCAGravityTop;
CATransform3D transform = CATransform3DMakeRotation(1.1/M_PI, 1.0, 0.0, 0.0);
transform.m34 = 1.0f / 2500.0f;
flipAnimationLayer.transform = transform;
currentAngle = startFlipAngle = 0;
endFlipAngle = M_PI;
} else {
//down
backLayer.contents = (id) [newImage CGImage];
backLayer.contentsGravity = kCAGravityBottom;
frontLayer.contents = (id) [currentImage CGImage];
frontLayer.contentsGravity = kCAGravityTop;
CATransform3D transform = CATransform3DMakeRotation(M_PI/1.1, 1.0, 0.0, 0.0);
transform.m34 = 1.0f / 2500.0f;
flipAnimationLayer.transform = transform;
currentAngle = startFlipAngle = M_PI;
endFlipAngle = 0;
}
}
- (void) cleanupFlip {
[backgroundAnimationLayer removeFromSuperlayer];
[flipAnimationLayer removeFromSuperlayer];
backgroundAnimationLayer = Nil;
flipAnimationLayer = Nil;
animating = NO;
if (setNextViewOnCompletion) {
[self.currentView removeFromSuperview];
self.currentView = self.nextView;
self.nextView = Nil;
} else {
[self.nextView removeFromSuperview];
self.nextView = Nil;
}
self.currentView.alpha = 1;
}
- (void) setFlipProgress:(float) progress setDelegate:(BOOL) setDelegate animate:(BOOL) animate {
if (animate) {
animating = YES;
}
float newAngle = startFlipAngle + progress * (endFlipAngle - startFlipAngle);
float duration = animate ? 0.5 * fabs((newAngle - currentAngle) / (endFlipAngle - startFlipAngle)) : 0;
currentAngle = newAngle;
CATransform3D endTransform = CATransform3DIdentity;
endTransform.m34 = 1.0f / 2500.0f;
endTransform = CATransform3DRotate(endTransform, newAngle, 1.0, 0.0, 0.0);
[flipAnimationLayer removeAllAnimations];
// shadows
//NSLog(#"End flip angle: %.0f, \tstartflip: %.0f, \tprogress: %.2f\tduration: %.2f", endFlipAngle, startFlipAngle,progress, duration);
CGFloat newShadowOpacity = (0.5 - progress);
if(newShadowOpacity < 0) {
newShadowOpacity *= -1;
}
if (newShadowOpacity < 0.05) {
newShadowOpacity = 0;
}
// shadows
if (duration < 0.15) {
duration = 0.15;
}
[UIView animateWithDuration: duration delay: 0 options: UIViewAnimationOptionCurveLinear animations: ^(void) {
flipAnimationLayer.transform = endTransform;
if (endFlipAngle < startFlipAngle) {
if(progress < 0.5) {
rightLayerShadow.opacity = newShadowOpacity;
frontLayerShadow.opacity = (0.5 - newShadowOpacity)/2;
} else {
backLayerShadow.opacity = (0.5 - newShadowOpacity)/2;
leftLayerShadow.opacity = newShadowOpacity;
}
} else {
if(progress < 0.5) {
leftLayerShadow.opacity = newShadowOpacity;
backLayerShadow.opacity = (0.5 - newShadowOpacity)/2;
} else {
frontLayerShadow.opacity = (0.5 - newShadowOpacity)/2;
rightLayerShadow.opacity = newShadowOpacity;
}
}
// shadows
} completion: ^(BOOL completion) {
}];
if (setDelegate) {
[self performSelector:#selector(cleanupFlip) withObject:Nil afterDelay:duration];
}
}
- (void) flipPage {
[self setFlipProgress:1.0 setDelegate:YES animate:YES];
}
#pragma mark -
#pragma mark Animation management
- (void)animationDidStop:(NSString *) animationID finished:(NSNumber *) finished context:(void *) context {
[self cleanupFlip];
}
#pragma mark -
#pragma mark Properties
#synthesize currentPage;
- (BOOL) doSetCurrentPage:(NSInteger) value {
if (value == currentPage) {
return FALSE;
}
flipDirection = value < currentPage ? AFKPageFlipperDirectionBottom : AFKPageFlipperDirectionTop;
currentPage = value;
self.nextView = [self.dataSource viewForPage:value inFlipper:self];
[self addSubview:self.nextView];
return TRUE;
}
- (void) setCurrentPage:(NSInteger) value {
if (![self doSetCurrentPage:value]) {
return;
}
setNextViewOnCompletion = YES;
animating = YES;
self.nextView.alpha = 0;
[UIView beginAnimations:#"" context:Nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(animationDidStop:finished:context:)];
self.nextView.alpha = 1;
[UIView commitAnimations];
}
- (void) setCurrentPage:(NSInteger) value animated:(BOOL) animated {
if (![self doSetCurrentPage:value]) {
return;
}
setNextViewOnCompletion = YES;
animating = YES;
if (animated) {
[self initFlip];
[self performSelector:#selector(flipPage) withObject:Nil afterDelay:0.091];
} else {
[self animationDidStop:Nil finished:[NSNumber numberWithBool:NO] context:Nil];
}
}
#synthesize dataSource;
- (void) setDataSource:(NSObject <AFKPageFlipperDataSource>*) value {
if (dataSource) {
dataSource = nil;
}
dataSource = value;
numberOfPages = [dataSource numberOfPagesForPageFlipper:self];
currentPage = 0;
self.currentPage = 1;
}
#synthesize disabled;
- (void) setDisabled:(BOOL) value {
disabled = value;
self.userInteractionEnabled = !value;
for (UIGestureRecognizer *recognizer in self.gestureRecognizers) {
recognizer.enabled = !value;
}
}
#pragma mark -
#pragma mark Touch management
- (void) tapped:(UITapGestureRecognizer *) recognizer {
if (animating || self.disabled) {
return;
}
if (recognizer.state == UIGestureRecognizerStateRecognized) {
NSInteger newPage;
if ([recognizer locationInView:self].y < (self.bounds.size.height - self.bounds.origin.y) / 2) {
newPage = MAX(1, self.currentPage - 1);
} else {
newPage = MIN(self.currentPage + 1, numberOfPages);
}
[self setCurrentPage:newPage animated:YES];
}
}
- (void) panned:(UIPanGestureRecognizer *) recognizer {
if (animating) {
return;
}
static BOOL hasFailed;
static BOOL initialized;
static NSInteger oldPage;
float translation = [recognizer translationInView:self].y;
float progress = translation / self.bounds.size.height;
if (flipDirection == AFKPageFlipperDirectionTop) {
progress = MIN(progress, 0);
} else {
progress = MAX(progress, 0);
}
switch (recognizer.state) {
case UIGestureRecognizerStateBegan:
hasFailed = FALSE;
initialized = FALSE;
animating = NO;
setNextViewOnCompletion = NO;
break;
case UIGestureRecognizerStateChanged:
if (hasFailed) {
return;
}
if (!initialized) {
oldPage = self.currentPage;
if (translation > 0) {
if (self.currentPage > 1) {
[self doSetCurrentPage:self.currentPage - 1];
} else {
hasFailed = TRUE;
return;
}
} else {
if (self.currentPage < numberOfPages) {
[self doSetCurrentPage:self.currentPage + 1];
} else {
hasFailed = TRUE;
return;
}
}
hasFailed = NO;
initialized = TRUE;
setNextViewOnCompletion = NO;
[self initFlip];
}
[self setFlipProgress:fabs(progress) setDelegate:NO animate:NO];
break;
case UIGestureRecognizerStateFailed:
[self setFlipProgress:0.0 setDelegate:YES animate:YES];
currentPage = oldPage;
break;
case UIGestureRecognizerStateRecognized:
if (hasFailed) {
[self setFlipProgress:0.0 setDelegate:YES animate:YES];
currentPage = oldPage;
return;
}
if (fabs((translation + [recognizer velocityInView:self].y / 4) / self.bounds.size.height) > 0.5) {
setNextViewOnCompletion = YES;
[self setFlipProgress:1.0 setDelegate:YES animate:YES];
} else {
[self setFlipProgress:0.0 setDelegate:YES animate:YES];
currentPage = oldPage;
}
break;
default:
break;
}
}
#pragma mark -
#pragma mark Frame management
/*
- (void) setFrame:(CGRect) value {
super.frame = value;
numberOfPages = [dataSource numberOfPagesForPageFlipper:self];
if (self.currentPage > numberOfPages) {
self.currentPage = numberOfPages;
}
}*/
#pragma mark -
#pragma mark Initialization and memory management
+ (Class) layerClass {
return [CATransformLayer class];
}
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self initRecognizers];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder: aDecoder])) {
[self initRecognizers];
}
return self;
}
- (void) initRecognizers {
_tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapped:)];
_panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(panned:)];
[_tapRecognizer requireGestureRecognizerToFail:_panRecognizer];
[self addGestureRecognizer:_tapRecognizer];
[self addGestureRecognizer:_panRecognizer];
}
#end
I am using Xcode 4.4 and target is iOS 5.
As on the title, I would like to create multiple pinch gestures for different images. I use two type of images. One is set as a background and the 2nd type of image is a stamp that is pasted on the image that is set as background. To do this I am using UIGestureRecognizer. Everything is fine until I paste the stamp type of image and try to zoom that image. I can zoom but when I zoom the image, the image has has been set as background zooms as well.
With the code below, I can paste different images (stamp type), tap and drag them individually but not when I try all the content zooms as well. Why isn't working?
Thank you in advance
- (void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSLog(#"menuListType=%# ; menuID=%#", self.category.menuListType ,self.menu.menuID);
UIImage *aImage;
NSString *imagepath = [NSString stringWithFormat:#"%#%#",[FileUtility getPDFImageFolderPath], self.menu.imageID];
if (self.menu.imageID == nil || [self.menu.imageID isEqualToString:#""]) {
// self.canvasView.image = [UIImage imageNamed:#"NotExistFile.jpg"];
aImage = [UIImage imageNamed:#"NotExistFile.jpg"];
} else {
// self.canvasView.image = [UIImage imageWithContentsOfFile:imagepath];
aImage = [UIImage imageWithContentsOfFile:imagepath];
// self.canvasView = [[[UIImageView alloc] initWithImage:self.canvasView.image] autorelease];
}
// Choose image base and set as background
if ([self.category.menuListType isEqualToString:#"4"]) {
//set size
int imageW = aImage.size.width;
int imageH = aImage.size.height;
float scale = (imageW > imageH ? 500.0f/imageH : 500.0f/imageW);
CGSize resizedSize = CGSizeMake(imageW * scale, imageH * scale);
UIGraphicsBeginImageContext(resizedSize);
[aImage drawInRect:CGRectMake(0, 0, resizedSize.width, resizedSize.height)];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.canvasView.contentMode = UIViewContentModeTop;
self.canvasView.image = resizedImage;
if (self.menu.imageID == nil || [self.menu.imageID isEqualToString:#""]) {
} else {
self.canvasView = [[[UIImageView alloc] initWithImage:self.canvasView.image] autorelease];
}
} else {
// Paste image and set as background
UIImage *captureImage;
NSString *capturepath = [NSString stringWithFormat:#"%#%#",[FileUtility getPDFImageFolderPath], #"capture.png"];
if ([FileUtility fileExist:capturepath]) {
captureImage = [UIImage imageWithContentsOfFile:capturepath];
} else {
captureImage = [UIImage imageNamed:#"NotExistFile3.png"];
}
self.canvasView.contentMode = UIViewContentModeTop;;
self.canvasView.image = captureImage;
self.canvasView = [[[UIImageView alloc] initWithImage:self.canvasView.image] autorelease];
// Prepare Gestures
iViewsTapidx = 0;
iViewsDblTapidx = 0;
ivMax = sizeof(iViews) / sizeof(iViews[0]);
isTaped = NO;
isDblTaped = NO;
_width = 100;
// Initialization code
// Single tap
UITapGestureRecognizer *tapg =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(tapAction:)];
[self.itemView addGestureRecognizer:tapg];
// Double tap
UITapGestureRecognizer *doubleTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(doubleTapAction:)];
doubleTap.numberOfTapsRequired = 2;
[self.itemView addGestureRecognizer:doubleTap];
// longPress(長押し)
UILongPressGestureRecognizer *longPress =
[[UILongPressGestureRecognizer alloc] initWithTarget:self
action:#selector(longPressAction:)];
[self.itemView addGestureRecognizer:longPress];
// drag
UIPanGestureRecognizer *pan =
[[UIPanGestureRecognizer alloc] initWithTarget:self
action:#selector(panAction:)];
[self.itemView addGestureRecognizer:pan];
//pinch
UIPinchGestureRecognizer *pinchGestureRognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(handlePinch:)];
[self.itemView addGestureRecognizer:pinchGestureRognizer];
// Stamp Image
int i = 0;
CGPoint tapPoint = CGPointMake(self.canvasView.center.x, self.canvasView.center.y);
int parcent = aImage.size.width / _width; // Prepare image to paste
// Show stamp
*(iViews+i) = [[UIImageView alloc] initWithImage:aImage];
(*(iViews+i)).frame = CGRectMake(tapPoint.x - aImage.size.width/parcent/2,
tapPoint.y - aImage.size.height/parcent/2,
aImage.size.width/parcent,
aImage.size.height/parcent);
(*(iViews+i)).tag = i+1;
[self.itemView addSubview:*(iViews+i)];
iViewsTapidx = i;
isTaped = YES;
self.itemView.userInteractionEnabled = YES;
}
[self showAnimation];
}
// tap
-(void)tapAction:(UITapGestureRecognizer *) sender{
CGPoint tapPoint = [sender locationInView:self.itemView];
NSLog(#">>>tap x=%.2f, y=%.2f", tapPoint.x, tapPoint.y);
int i =0;
isTaped = NO;
for (i = 0; i < ivMax; i++) {
if (CGRectContainsPoint((*(iViews+i)).frame, tapPoint)) {
isTaped = YES;
iViewsTapidx = i;
NSLog(#"i = %d", i);
break;
}
}
}
// doubleTap
-(void)doubleTapAction:(UITapGestureRecognizer *) sender{
NSLog(#">>>doubleTap");
CGPoint tapPoint = [sender locationInView:self.itemView];
isTaped = NO;
isDblTaped = NO;
int i =0;
for (i = 0; i < ivMax; i++) {
if (CGRectContainsPoint((*(iViews+i)).frame, tapPoint)) {
isDblTaped = YES;
iViewsDblTapidx = i;
break;
}
}
// remove
if (isDblTaped) {
NSLog(#"remove %d", i);
(*(iViews+i)).tag = 0;
[*(iViews+i) removeFromSuperview];
}
}
// longPress
- (void)longPressAction:(UILongPressGestureRecognizer *) sender{
if ([sender state] == UIGestureRecognizerStateBegan) {
NSLog(#">>>longPress 1");
}else if ([sender state] == UIGestureRecognizerStateEnded) {
CGPoint tapPoint = [sender locationInView:self.itemView];
NSLog(#">>>longPress 2 x=%.2f, y=%.2f", tapPoint.x, tapPoint.y);
int i =0;
for (i = 0; i < ivMax; i++) {
NSLog(#"i = %d", i);
if ((*(iViews+i)).tag == 0) {
break;
}
}
if (i < ivMax) {
//Stamp imapge
UIImage *stampImage;
NSString *imagepath = [NSString stringWithFormat:#"%#%#",[FileUtility getPDFImageFolderPath], self.menu.imageID];
if (self.menu.imageID == nil || [self.menu.imageID isEqualToString:#""]) {
stampImage = [UIImage imageNamed:#"NotExistFile.jpg"];
} else {
stampImage = [UIImage imageWithContentsOfFile:imagepath];
}
int parcent = stampImage.size.width / _width; // Set stamp image
//Sow stamp image
*(iViews+i) = [[UIImageView alloc] initWithImage:stampImage];
(*(iViews+i)).frame = CGRectMake(tapPoint.x - stampImage.size.width/parcent/2,
tapPoint.y - stampImage.size.height/parcent/2,
stampImage.size.width/parcent,
stampImage.size.height/parcent);
(*(iViews+i)).tag = i+1;
[self.itemView addSubview:*(iViews+i)];
iViewsTapidx = i;
isTaped = YES;
}
}
}
// drag
- (void)panAction:(UIPanGestureRecognizer *) sender{
NSLog(#">>>pan");
if (isTaped) {
CGPoint p = [sender translationInView:self.itemView];
CGPoint movePoint = CGPointMake((*(iViews+iViewsTapidx)).center.x + p.x,
(*(iViews+iViewsTapidx)).center.y + p.y);
(*(iViews+iViewsTapidx)).center = movePoint;
// NSLog(#">>>pan x=%.2f, y=%.2f --> x=%.2f, y=%.2f", p.x, p.y, movePoint.x, movePoint.y);
NSLog(#">>>pan x=%.2f, y=%.2f", p.x, p.y);
[sender setTranslation:CGPointZero inView:self.itemView];
}
}
-(void) handlePinch:(UIGestureRecognizer *) sender {
UIPinchGestureRecognizer *pinchGesture = (UIPinchGestureRecognizer *) sender;
if (pinchGesture.state == UIGestureRecognizerStateBegan || pinchGesture.state == UIGestureRecognizerStateChanged) {
//UIView *view = pinchGesture.view;
// UIView *view = self.itemView;
self.itemView.transform = CGAffineTransformScale(self.itemView.transform, pinchGesture.scale, pinchGesture.scale);
pinchGesture.scale = 1;
NSLog(#"zoom");
}
}
You will have to add Gesture Recognizer on Uiimageview, Look here for doing so : UIGestureRecognizer on UIImageView
Yet another way is to use UIScrolliew as your container instead of UIView and use the - (UIView*)viewForZoomingInScrollView:(UIScrollView *)aScrollView {
return imageView;
}
here imageView is the image you want to zoom,this will zoom that only image you are pinching its tested and works fine.
The following is my code, it's working properly, it's just that the "animation" of a moving line in the line if (guidelineOn) is not smooth. The drawRect is being called every 0.01 seconds.
if (guideLineOn)
{
[self drawGuidanceLineAtPoint:CGPointMake((65+guideLineOffset)*scalingF, 98*scalingF) withAlpha:paramAlpha];
}
It's kind of laggy and sometimes interferes with the user input. How do I resolve this? New to this so open to suggestions.
Thanks in advance for your help.
Pier.
- (void)drawRect:(CGRect)rect
{
scalingF = 1.0; // default : iPhone
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
scalingF = IPAD_SCALING_FACTOR;
}
if (guideLineOn)
{
[self drawGuidanceLineAtPoint:CGPointMake((65+guideLineOffset)*scalingF, 98*scalingF) withAlpha:paramAlpha];
}
// draw staff line
[self drawStaffLineFrom:CGPointMake(65*scalingF, 98*scalingF) toPoint:CGPointMake(420*scalingF, 98*scalingF)];
[self drawStaffLineFrom:CGPointMake(420*scalingF,108*scalingF) toPoint:CGPointMake(420*scalingF, 50*scalingF)];
[self drawStaffLineFrom:CGPointMake(415*scalingF,108*scalingF) toPoint:CGPointMake(415*scalingF, 50*scalingF)];
// cycle through all the static images to draw tbd
float offSet = 0.0;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
offSet += 50.0; // to adjust the metronome down
}
if (metronomeImage)
{
[metronomeImage drawInRect:CGRectMake(410.0f*scalingF, 195.0f*scalingF+offSet, metronomeImage.size.width*scalingF, metronomeImage.size.height*scalingF)];
}
if (circlesImage)
{
[circlesImage drawInRect:CGRectMake(400.0f*scalingF, 255.0f*scalingF+offSet, circlesImage.size.width*scalingF, circlesImage.size.height*scalingF)];
}
for (Note * v in notesArray)
{
UIImage * noteImage = [UIImage imageNamed: v.imageName];
[noteImage drawInRect:CGRectMake(v.notePlacement.x*scalingF, v.notePlacement.y*scalingF, noteImage.size.width*scalingF, noteImage.size.height*scalingF)];
}
if (!clearDisplay)
{
// draw the arrows
for (int i=0; i < arrowsToDrawArray.count; i++)
{
Arrow * arrowObj = [arrowsToDrawArray objectAtIndex:i];
UIColor * colourOfArrow = [arrowObj colourOfArrow]; // colour determines whether right or wrong
CGPoint p = [arrowObj arrowPlacement];
p.x = p.x*scalingF;
p.y = p.y*scalingF;
// CGPoint p = [val CGPointValue];
[self drawRooftopAtTopPointof:p colour:colourOfArrow lineJoin:kCGLineJoinMiter];
}
// draw the ties
for (int j=0; j < tiePointsArray.count; j++)
{
CGPointPair * tiePairToDraw = [tiePointsArray objectAtIndex:j];
CGPoint firstPt = [tiePairToDraw firstPoint];
firstPt.x = firstPt.x *scalingF;
firstPt.y = firstPt.y *scalingF;
CGPoint secondPt = [tiePairToDraw secondPoint];
secondPt.x = secondPt.x *scalingF;
secondPt.y = secondPt.y *scalingF;
[self drawPseudoCurveFromPoint:firstPt toPoint:secondPt];
}
// bool perfect = true;
// int noOfNotesHit = 0;
// draw the tick/cross/arrow
for (int k=0; k < answerObjArray.count; k++)
{
Answer * ansObj = [answerObjArray objectAtIndex:k];
if (ansObj.hit)
{
// noOfNotesHit++;
if (ansObj.earlyOrLate == -1) // early, draw right pointing arrow
{
UIImage * arrowImage = [UIImage imageNamed: #"arrowright.png"];
[arrowImage drawInRect:CGRectMake((ansObj.xPosition-(0.5*arrowImage.size.width))*scalingF, 125*scalingF, arrowImage.size.width*scalingF, arrowImage.size.height*scalingF)];
// perfect = false;
}
else if (ansObj.earlyOrLate == 1) // late, draw left pointing arrow
{
UIImage * arrowImage = [UIImage imageNamed: #"arrowleft.png"];
[arrowImage drawInRect:CGRectMake((ansObj.xPosition-(0.5*arrowImage.size.width))*scalingF, 125*scalingF, arrowImage.size.width*scalingF, arrowImage.size.height*scalingF)];
//perfect = false;
}
else // perfect!
{
// draw a tick
UIImage * tickImage = [UIImage imageNamed: #"tick.png"];
[tickImage drawInRect:CGRectMake((ansObj.xPosition-(0.5*tickImage.size.width))*scalingF, 125*scalingF, tickImage.size.width*scalingF, tickImage.size.height*scalingF)];
}
}
else
{
// draw a cross
UIImage * crossImage = [UIImage imageNamed: #"cross.png"];
[crossImage drawInRect:CGRectMake((ansObj.xPosition-(0.5*crossImage.size.width))*scalingF, 125*scalingF, crossImage.size.width*scalingF, crossImage.size.height*scalingF)];
//perfect = false;
}
}
}
else
{
// draw nothing
clearDisplay = false;
}
}
Here's my Core Animation solution for those interested.
- (void) animateRedLine: (float) alphaParam
{
[self.view addSubview:self.redlineImageView];
/* Start from top left corner */
[self.redlineImageView setFrame:CGRectMake(65.0f*scalingF,
50.0f*scalingF,
self.redlineImageView.image.size.width*scalingF,
self.redlineImageView.image.size.height*scalingF*2)];
[self.redlineImageView setAlpha:alphaParam];
[UIView beginAnimations:#"redLineAnimation"
context:( void *)self.redlineImageView];
/* 3 seconds animation */
[UIView setAnimationDuration:noOfBeatsInBar*timeInSecondsForOneBeat];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
/* Receive animation delegates */
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:
#selector(imageViewDidStop:finished:context:)];
/* End at the bottom right corner */
[self.redlineImageView setFrame:CGRectMake((65.0f+LENGTH_OF_BAR)*scalingF,
50.0f*scalingF,
self.redlineImageView.image.size.width*scalingF,
self.redlineImageView.image.size.height*scalingF*2)];
//[self.redlineImageView setAlpha:0.0f];
[UIView commitAnimations];
}