iOS layerios
//捏合手勢方法。數組
-(void)pinchAction:(id)sender{app
NSLog(@"捏合");框架
UIPinchGestureRecognizer *pin=(UIPinchGestureRecognizer *)sender;dom
// self.myImageV.transform=CGAffineTransformMakeScale(pin.scale, pin.scale);curl
pin.view.transform = CGAffineTransformScale(pin.view.transform, pin.scale, pin.scale);ide
pin.scale = 1;函數
float tempF = self.myImageV.size.height/self.myImageV.size.width;oop
if (self.myImageV.size.width<150) {佈局
self.myImageV.size = CGSizeMake(150, 150*tempF);
}
}
#if 0
//1iOS-對CALayer的最簡單使用
iOS的Core Animation,有不少概念,包括Layer(層)、Animation(動畫)和Timing(時序)、Layout(佈局)和constraint(約束)、Transaction(處理)。其中Layer是最基礎的。
Layer有多種,最基本的是CALayer,它也是其餘種類Layer的父類。CALayer的子類有:
CAScrollLayer,用於簡化顯示層的一部分
CATextLayer,便於從字符串生成內容是文本的層
CATiledLayer,可用於顯示覆雜的圖片
CAOpenGLLayer,提供OpenGLES渲染環境
Core Animation是基於QuartzCore的,須要在項目中引入框架
編寫iOS視圖UIView的動畫效果須要不少代碼,雖然iOS 4支持塊定義,對視圖動畫的定義減小了很多代碼,但語法依舊很差看。CPAnimationSequence是一個開源代碼庫,能夠一種間接快捷的方式來定義描述動畫隊列,克服了寫繁多的代碼。下面一個使用例子:
查看源碼打印?
01
CPAnimationSequence* shakespeare = [CPAnimationSequence sequenceWithSteps:
02
[CPAnimationStep for:0.2 animate:^{ self.romeo.alpha = 1.0; }],
03
[CPAnimationStep for:0.2 animate:^{ self.julia.alpha = 1.0; }],
04
[CPAnimationStep after:1.0 for:0.7 animate:^{
05
CGPoint love = CGPointMake((self.romeo.center.x + self.julia.center.x)/2,
06
(self.romeo.center.y + self.julia.center.y)/2);
07
self.romeo.center = love;
08
self.julia.center = love;
09
}],
10
[CPAnimationStep after:2.0 for:0.5 animate:^{ self.romeo.alpha = 0.0;
11
self.julia.alpha = 0.0; }]
12
nil];
13
[shakespeare run];
官方網站:http://www.open-open.com/lib/view/home/1326072094546
-(void)loadSimpleImageAnimation{
//建立圖片對象
UIImage *image = [UIImage imageNamed:@"6.png"];
//建立層
CALayer *layer = [CALayer layer];
layer.backgroundColor = [[UIColor blackColor] CGColor];//設置背景色
layer.bounds = CGRectMake(0, 0, image.size.width,image.size.height);//層設置爲圖片大小
layer.contents = (id)[image CGImage];//層的內容設置爲圖片
layer.position = CGPointMake(1024/2 , 768/2);//層在view的位置
[self.view.layer addSublayer:layer];//將層加到當前View的默認layer下
[layer release];
[image release];
}
第二種方式相對複雜一些,但若是更好的進行控制,仍是使用這種方法吧,
基本使用方法能夠看一下以下例子:
CATransition *animation = [CATransition animation];
[animation setDuration:1.25f];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
[animation setType:kCATransitionReveal];
[animation setSubtype: kCATransitionFromBottom];
[self.view.layer addAnimation:animation forKey:@"Reveal"];
這裏使用了setType與setSubtype組合,這使用個比較保險,由於他的參數就是官方API裏定義的,他們的參數說明能夠參考以下:
[animation setType:@"suckEffect"];
這裏的suckEffect就是效果名稱,能夠用的效果主要有:
rippleEffect 滴水效果
suckEffect 收縮效果,如一塊布被抽走
cube 立方體效果
oglFlip 上下翻轉效果
最後再給出一種經常使用代碼供你們參考。
CATransition *animation = [CATransition animation];
[animation setDuration:0.35];
[animation setTimingFunction:UIViewAnimationCurveEaseInOut];
if (!curled)
{
//animation.type = @"mapCurl";
animation.type = @"pageCurl";
animation.fillMode = kCAFillModeForwards;
animation.endProgress = 0.99;
} else {
//animation.type = @"mapUnCurl";
animation.type = @"pageUnCurl";
animation.fillMode = kCAFillModeBackwards; animation.startProgress = 0.01;
}
[animation setRemovedOnCompletion:NO];
[view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
[view addAnimation:animation forKey"pageCurlAnimation"];
// Disable user interaction where necessary
if (!curled) {
}
else {
}
curled = !curled;
一.基本方式:使用UIView類的UIViewAnimation擴展
函數說明
+ (void)beginAnimations:(NSString *)animationID context:(void *)context; // 開始準備動畫
+ (void)commitAnimations; // 運行動畫
// 沒有get方法,下面的set在快外調用無效
+ (void)setAnimationDelegate:(id)delegate; // 委託default = nil
+ (void)setAnimationWillStartSelector:(SEL)selector; // default = NULL. -animationWillStart:(NSString *)animationID context:(void *)context
+ (void)setAnimationDidStopSelector:(SEL)selector; // default = NULL. -animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
+ (void)setAnimationDuration:(NSTimeInterval)duration; // default = 0.2動畫時間
+ (void)setAnimationDelay:(NSTimeInterval)delay; // default = 0.0延遲多少時間開始執行動畫
+ (void)setAnimationStartDate:(NSDate *)startDate; // default = now ([NSDate date])動畫開始日期?不知道啥用.- -
+ (void)setAnimationCurve:(UIViewAnimationCurve)curve; // default = UIViewAnimationCurveEaseInOut動畫方式
+ (void)setAnimationRepeatCount:(float)repeatCount; // default = 0.0. May be fractional重複次數
+ (void)setAnimationRepeatAutoreverses:(BOOL)repeatAutoreverses; // default = NO. YES的話,動畫(非最後一次)結束後動態復原到最開始狀態
+ (void)setAnimationBeginsFromCurrentState:(BOOL)fromCurrentState; // default = NO. YES,中止以前的動畫,從如今這裏開始新動畫the current view position is always used for new animations -- allowing animations to "pile up" on each other. Otherwise, the last end state is used for the animation (the default).
+ (void)setAnimationTransition:(UIViewAnimationTransition)transition forView:(UIView *)view cache:(BOOL)cache; // 添加動畫到view上,cache是YES的時候比較高效,可是動畫過程當中不能更新界面上的內容,NO時每一幀都從新畫,能夠實時更新
+ (void)setAnimationsEnabled:(BOOL)enabled; // 是否忽略一些動畫設置
+ (BOOL)areAnimationsEnabled;
一個動畫的代碼
[UIView beginAnimations:nil context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[UIView setAnimationDuration:2.7];
[UIView setAnimationTransition:transition forView:self.view cache:YES];
// operation>>>
[self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
// end<<<<<<
[UIView commitAnimations];
其中transition取值範圍
typedefenum {
UIViewAnimationTransitionNone,
UIViewAnimationTransitionFlipFromLeft,
UIViewAnimationTransitionFlipFromRight,
UIViewAnimationTransitionCurlUp,
UIViewAnimationTransitionCurlDown,
} UIViewAnimationTransition;
特色:基礎,使用方便,可是效果有限
二.block方式:使用UIView類的UIViewAnimationWithBlocks擴展
函數說明
+ (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOLfinished))completion __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_0);//間隔,延遲,動畫參數(好像沒用?),界面更改塊,結束塊
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_0); // delay = 0.0, options = 0
+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_0); // delay = 0.0, options = 0, completion = NULL
+ (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOLfinished))completion __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_0);
+ (void)transitionFromView:(UIView *)fromView toView:(UIView *)toView duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options completion:(void (^)(BOOL finished))completion __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_0); // toView added to fromView.superview, fromView removed from its superview界面替換,這裏的options參數有效
舉例:
[UIView animateWithDuration:0.7 delay:0 options:0 animations:^(){
self.view.alpha = 0.2;
[self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:0];
self.view.alpha = 1;
} completion:^(BOOL finished)
{
}];
當areAnimationsEnabled爲NO時,上面不能動畫顯示
[UIView transitionFromView:lImage toView:mImage duration:0.7 options:options completion:^(BOOL finished)
{
if (finished) {
[self.view addSubview:lImage];
[self.view sendSubviewToBack:lImage];
[self.view sendSubviewToBack:mImage];
}
}];
options取值範圍
enum {
UIViewAnimationOptionLayoutSubviews = 1 << 0,
UIViewAnimationOptionAllowUserInteraction = 1 << 1, // turn on user interaction while animating
UIViewAnimationOptionBeginFromCurrentState = 1 << 2, // start all views from current value, not initial value
UIViewAnimationOptionRepeat = 1 << 3, // repeat animation indefinitely
UIViewAnimationOptionAutoreverse = 1 << 4, // if repeat, run animation back and forth
UIViewAnimationOptionOverrideInheritedDuration = 1 << 5, // ignore nested duration
UIViewAnimationOptionOverrideInheritedCurve = 1 << 6, // ignore nested curve
UIViewAnimationOptionAllowAnimatedContent = 1 << 7, // animate contents (applies to transitions only)
UIViewAnimationOptionShowHideTransitionViews = 1 << 8, // flip to/from hidden state instead of adding/removing
UIViewAnimationOptionCurveEaseInOut = 0 << 16, // default
UIViewAnimationOptionCurveEaseIn = 1 << 16,
UIViewAnimationOptionCurveEaseOut = 2 << 16,
UIViewAnimationOptionCurveLinear = 3 << 16,
UIViewAnimationOptionTransitionNone = 0 << 20, // default
UIViewAnimationOptionTransitionFlipFromLeft = 1 << 20,
UIViewAnimationOptionTransitionFlipFromRight = 2 << 20,
UIViewAnimationOptionTransitionCurlUp = 3 << 20,
UIViewAnimationOptionTransitionCurlDown = 4 << 20,
UIViewAnimationOptionTransitionCrossDissolve = 5 << 20,//ios5
UIViewAnimationOptionTransitionFlipFromTop = 6 << 20,//ios5
UIViewAnimationOptionTransitionFlipFromBottom = 7 << 20,//ios5
};
typedef NSUInteger UIViewAnimationOptions;
特色:快捷方便,效果更多.能夠如上示例1那樣實現界面個元素屬性漸進變化的動態展現
三.core方式:使用CATransition類
使用要引入QuartzCore.framework
官方有個示例:ViewTransitions
基本上就是
CATransition *transition = [CATransition animation];
transition.duration = 0.7;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionMoveIn;//{kCATransitionMoveIn, kCATransitionPush, kCATransitionReveal, kCATransitionFade};
//更多私有{@"cube",@"suckEffect",@"oglFlip",@"rippleEffect",@"pageCurl",@"pageUnCurl",@"cameraIrisHollowOpen",@"cameraIrisHollowClose"};
transition.subtype = kCATransitionFromLeft;//{kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom};
transition.delegate = self;
[self.view.layer addAnimation:transition forKey:nil];
// 要作的
[self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:0];
UIView *aView=[[[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds]autorelease];
[self.view addSubview:aView];
//若是單純的用UITouch 的時候只能用上面的,不能用下面的。
self.view=[[[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds]autorelease];
//2
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
CGRect frame1=touch.view.frame;
CGRect frame2=bView.frame;
if (frame1.origin.x==frame2.origin.x) {
//旋轉。。
CGAffineTransform transform;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2];
transform=CGAffineTransformRotate(bView.transform, M_PI/3);//相對的。
// transform=CGAffineTransformMakeRotate(M_PI/3);//這裏是絕對的。
bView.transform=transform;
[UIView commintModelAnimations];
//還原.
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2];
bView.transform=CGAffineTransformMakeScale(1.0f, 1.0f);
[UIView commintModelAnimations];
//翻轉。
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:bView cache:YES];
[UIView commintModelAnimations];
}
}
//3,用層,時須要QuartzCore/QuartzCore.h框架。
RootViewController *rootVC=[[RootViewController alloc] init];
self.window.rootViewController=rootVC;
[rootVC release];
//4用一個代理和一個類目實現順序執行動畫。
@interface UIViewDelegate : NSObject
{
CFRunLoopRef currentLoop;
}
-(id)initWithRunLoop:(CFRunLoopRef)runLoop;
-(void)animationFinished:(id)sender;
@end
@implementation UIViewDelegate
-(id)initWithRunLoop:(CFRunLoopRef)runLoop
{
self=[super init];
if (self) {
currentLoop=runLoop;
}
returnself;
}
-(void)animationFinished:(id)sender
{
CFRunLoopStop(currentLoop);
}
@end
@interface UIView (ModalAnimationHelper)
+(void)commintModelAnimations;
@end
#import "UIView+ModalAnimationHelper.h"
#import "UIViewDelegate.h"
@implementation UIView (ModalAnimationHelper)
+(void)commintModelAnimations
{
CFRunLoopRef currentLoop=CFRunLoopGetCurrent();
UIViewDelegate *uivdelegete=[[UIViewDelegate alloc] initWithRunLoop:currentLoop];
[UIView setAnimationDelegate:uivdelegete];
[uivdelegete release];
[UIView setAnimationDidStopSelector:@selector(animationFinished:)];
[UIView commitAnimations];
CFRunLoopRun();
}
@end
//5按鈕控制的圖片組合的動畫。
self.view=[[[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds]autorelease];
[self.view setBackgroundColor:[UIColor grayColor]];
imageView=[[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 300)];
images=[[NSMutableArray alloc]initWithCapacity:8];
for (int i=0;i<8; i++) {
UIImage *image=[UIImage imageNamed:[NSString stringWithFormat:@"h%d.jpeg",i+1]];
[images addObject:image];
}
imageView.animationImages=images;
[images release];
imageView.animationDuration=8;
//建立開始按鈕。
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(100, 400, 150, 50);
[button setTitle:@"開始/中止" forState:UIControlStateNormal];
[button addTarget:self action:@selector(doStartOrStop) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[self.view addSubview:imageView];
[imageView release];
}
-(void)doStartOrStop{
if (m==0) {
[imageView startAnimating];
m=1;
}
else{
[imageView stopAnimating];
m=0;
}
}
//6觸摸事件。
1.單擊縮小視圖。:
CGRect myFrame = self.view.frame;
myFrame.size.width -= self.frame.size.width * 0.1;
myFrame.size.height -= self.frame.size.height * 0.1;
myFrame.origin.x += (self.frame.origin.x * 0.1) / 2.0;
myFrame.origin.y += (self.frame.origin.y * 0.1) / 2.0;
[UIView beginAnimations:nil context:NULL];
[self.view setFrame:myFrame];
[UIView commitAnimations];
2.移動
UITouch *theTouch=[touches anyObject];
CGPoint currentTouchPosition=[theTouch locationInView:self];
if ((fabs(startTouchPosition.x-currentTouchPosition.x)>4&&fabs(startTouchPosition.y-currentTouchPosition.y)<=12)) {
if (startTouchPosition.x<currentTouchPosition.x) {
NSLog(@"swipe to right");
}
else{
NSLog(@"swipe to left");
}
}
CGPoint prevTouchPosition=[theTouch previousLocationInView:self];
CGRect viewFrame=self.frame;
float deltaX=currentTouchPosition.x-prevTouchPosition.x;
float deltaY=currentTouchPosition.y-prevTouchPosition.y;
viewFrame.origin.x+=deltaX;
viewFrame.origin.y+=deltaY;
[self setFrame:viewFrame];
UITouch *theTouch = [touches anyObject];
if (theTouch.tapCount == 2) {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
}
startTouchPosition=[theTouch locationInView:self];
UIPinchGestureRecognizer *pinch=[[[UIPinchGestureRecognizer alloc]initWithTarget:selfaction:@selector(doPinch:)]autorelease];
[self addGestureRecognizer:pinch];
if (pinch.state==UIGestureRecognizerStateBegan) {
initialFontSize=label.font.pointSize;
}
else{
// label.font=[label.font fontWithSize:initialFontSize *pinch.scale];
self.frame=CGRectMake(self.frame.origin.x * pinch.scale,self.frame.origin.y * pinch.scale , self.frame.size.width *pinch.scale , self.frame.size.height *pinch.scale);
}
//7
//畫一個正方形沒有邊框。
CGContextSetRGBFillColor(context, 0, 0.25, 0, 0.5);//建立設置顏色。最後一位是透明度。
CGContextFillRect(context, CGRectMake(2, 2, 70, 70));
CGContextStrokePath(context);
//寫文字
CGContextSetLineWidth(context, 1.0);
CGContextSetRGBFillColor (context, 1, 1, 1, 1.0);
UIFont *font = [UIFont boldSystemFontOfSize:11.0];
[@"劉德華" drawInRect:CGRectMake(40, 40, 80, 20) withFont:font];
//畫一條線
CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 0.5);//線條顏色
CGContextMoveToPoint(context, 20, 20);
CGContextAddLineToPoint(context, 200,20);
CGContextStrokePath(context);
//畫正方形邊框
CGContextSetRGBStrokeColor(context, 1, 1.0, 1.0, 1.0);
CGContextSetLineWidth(context, 2.0);
CGContextAddRect(context, CGRectMake(200, 200, 70, 70));
CGContextStrokePath(context);
CGContextDrawPath(context, kCGPathFillStroke);
//畫一條線
CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 0.5);//線條顏色
CGContextMoveToPoint(context, 20, 20);
CGContextAddLineToPoint(context, 200,20);
CGContextStrokePath(context);
//8 關燈遊戲。
-(void)drawRect:(CGRect)rect{
//循環生成28個view。
for (int i=1; i<=54; i++) {
UIView *xiaoDengView=[[UIView alloc]init];
xiaoDengView.tag=i;
if (m==6) {
m=0;
n++;
}
xiaoDengView.frame=CGRectMake(79*m-150, 0+64*n-125, 70, 46);
xiaoDengView.backgroundColor=[UIColor redColor];
m++;
[self addSubview:xiaoDengView];
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *theTouch=[touches anyObject];
a=theTouch.view.tag;//肯定視圖標籤。
if (theTouch.tapCount==1) {
UIView *view1=[self viewWithTag:a];
UIView *view2=[self viewWithTag:(a+1)];
UIView *view3=[self viewWithTag:(a-1)];
UIView *view4=[self viewWithTag:(a+6)];
UIView *view5=[self viewWithTag:(a-6)];
//分別判斷5個視圖。
if ([view1.backgroundColor isEqual:[UIColor redColor]]) {
view1.backgroundColor=[UIColor blueColor];
}
else if([view1.backgroundColor isEqual:[UIColor blueColor]]){
view1.backgroundColor=[UIColor redColor];
}.......
}
}
//9輕拍",@"長按",@"輕掃",@"旋轉",@"捏合",@"拖拽"
self.imageView=[[[UIImageView alloc]initWithFrame:CGRectMake(50, 40, 220, 320)]autorelease];
self.imageView.image=[UIImage imageNamed:@"h1.jpeg"];
self.imageView.userInteractionEnabled=YES;
[self.view addSubview:self.imageView];
//建立一個數組,該數組用於顯示到segment上的文字。//單選按鈕。
NSArray *titles=[NSArray arrayWithObjects:@"輕拍",@"長按",@"輕掃",@"旋轉",@"捏合",@"拖拽",nil];
//建立UISegmentControl
UISegmentedControl *segment=[[UISegmentedControl alloc]initWithItems:titles];
segment.frame=CGRectMake(0, 420, 320, 40);
//爲UISegmentControl添加方法。
segment.selectedSegmentIndex=0;
[segment addTarget:self action:@selector(clickSegment:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:segment];
[segment release];
//設置默認。
//建立輕拍手勢,指定輕拍響應方法。
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
tap.numberOfTapsRequired=1;//默認爲1.表示點擊的次數。
//爲imageView添加手勢
[self.imageView addGestureRecognizer:tap];
[tap release];
//動畫按鈕。
UIButton *startButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
startButton.frame=CGRectMake(50, 370, 100, 40);
[startButton addTarget:self action:@selector(startAction:) forControlEvents:UIControlEventTouchUpInside];
[startButton setTitle:@"動畫開始" forState:UIControlStateNormal];
[self.view addSubview:startButton];
UIButton *stopButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
stopButton.frame=CGRectMake(170, 370, 100, 40);
[stopButton addTarget:self action:@selector(stopAction:) forControlEvents:UIControlEventTouchUpInside];
[stopButton setTitle:@"動畫中止" forState:UIControlStateNormal];
[self.view addSubview:stopButton];
//動畫播放速度。
UISlider *slider=[[UISlider alloc]initWithFrame:CGRectMake(60, 5, 200, 20)];
slider.minimumValue=0.1;
slider.maximumValue=1.0;
slider.value=1;
[slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:slider];
[slider release];
}
-(void)clickSegment:(id)sender{
UISegmentedControl *segment=(UISegmentedControl *)sender;
//移除手勢
for (UIGestureRecognizer *ges in self.imageView.gestureRecognizers) {
[self.imageView removeGestureRecognizer:ges];
}
//添加新的手勢。
switch (segment.selectedSegmentIndex) {
case 0:
{
//建立輕拍手勢,指定輕拍響應方法。
UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
tap.numberOfTapsRequired=1;//默認爲1.表示點擊的次數。
//爲imageView添加手勢
[self.imageView addGestureRecognizer:tap];
[tap release];
}
break;
case 1:
{
//長按手勢
UILongPressGestureRecognizer *longPress=[[UILongPressGestureRecognizer alloc]initWithTarget:selfaction:@selector(longPressAction:)];
[self.imageView addGestureRecognizer:longPress];
[longPress release];
}
break;
case 2:
{
//輕掃。
// for (int i=1; i<=8; i=i*2) {
// UISwipeGestureRecognizer *swip=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
// swip.direction=i;
// [self.imageView addGestureRecognizer:swip];
// [swip release];
// }
}
break;
case 3:
{
//旋轉。
UIRotationGestureRecognizer *rotation=[[UIRotationGestureRecognizer alloc]initWithTarget:selfaction:@selector(rotationAction:)];
rotation.rotation=9;//旋轉的弧度。
[self.imageView addGestureRecognizer:rotation];
[rotation release];
}
break;
case 4:
{
//捏合。
UIPinchGestureRecognizer *pinch=[[UIPinchGestureRecognizer alloc]initWithTarget:selfaction:@selector(pinchAction:)];
[self.imageView addGestureRecognizer:pinch];
[pinch release];
}
break;
case 5:
{
//拖拽。
UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc]initWithTarget:selfaction:@selector(panAction:)];
[self.imageView addGestureRecognizer:pan];
[pan release];
}
break;
default:
break;
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch=[touches anyObject];
startPoint=[touch locationInView:self.view];
}
//-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
// UITouch *touch=[touches anyObject];
// CGPoint currentPoint=[touch locationInView:self.view];
// if (fabs(startPoint.x-currentPoint.x)>=4&&(fabs(startPoint.y-currentPoint.y)<=12)) {
// NSLog(@"輕掃");
// NSString *imageName=[NSString stringWithFormat:@"h%d.jpeg",arc4random()%7+1];
// self.imageView.image=[UIImage imageNamed:imageName];
// }
//}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[touches anyObject];
CGPoint currentPoint=[touch locationInView:self.view];
if (fabs(startPoint.x-currentPoint.x)>=4&&(fabs(startPoint.y-currentPoint.y)<=12)) {
NSLog(@"輕掃");
NSString *imageName=[NSString stringWithFormat:@"h%d.jpeg",arc4random()%7+1];
self.imageView.image=[UIImage imageNamed:imageName];
}
}
//輕拍手勢方法。
-(void)tapAction:(id)sender{
NSLog(@"輕拍");
NSString *imageName=[NSString stringWithFormat:@"h%d.jpeg",arc4random()%7+1];
self.imageView.image=[UIImage imageNamed:imageName];
}
//長按手勢方法。
-(void)longPressAction:(id)sender{
NSLog(@"長按");
NSString *imageName=[NSString stringWithFormat:@"h%d.jpeg",arc4random()%7+1];
self.imageView.image=[UIImage imageNamed:imageName];
}
//輕掃手勢方法。
-(void)swipeAction:(id)sender{
NSLog(@"輕掃");
NSString *imageName=[NSString stringWithFormat:@"h%d.jpeg",arc4random()%7+1];
self.imageView.image=[UIImage imageNamed:imageName];
}
//旋轉手勢方法。
-(void)rotationAction:(id)sender{
NSLog(@"旋轉");
UIRotationGestureRecognizer *ro=(UIRotationGestureRecognizer *)sender;
self.imageView.transform=CGAffineTransformMakeRotation(ro.rotation);
}
//捏合手勢方法。
-(void)pinchAction:(id)sender{
NSLog(@"捏合");
UIPinchGestureRecognizer *pin=(UIPinchGestureRecognizer *)sender;
self.imageView.transform=CGAffineTransformMakeScale(pin.scale, pin.scale);
}
//拖拽手勢方法。
-(void)panAction:(id)sender{
NSLog(@"拖拽");
UIPanGestureRecognizer *pan=(UIPanGestureRecognizer *)sender;
if (pan.state==UIGestureRecognizerStateBegan) {//拖拽開始。
//記錄最初的座標點。
oldPoint=[pan locationInView:self.view];
}
//當前的座標點,並計算偏移量。
CGPoint newPoint=[pan locationInView:self.view];
CGFloat offSetX=newPoint.x-oldPoint.x;
CGFloat offSetY=newPoint.y-oldPoint.y;
//爲ImageView的中心賦值。
self.imageView.center=CGPointMake(pan.view.center.x+offSetX, pan.view.center.y+offSetY);
//保留已經用過的座標點。
oldPoint =newPoint;
}
//開始動畫。
-(void)startAction:(id)sender{
//建立數組,保存一組圖片。
NSMutableArray *mArray=[[NSMutableArray alloc]init];
for (int i=1; i<=6; i++) {
NSString *imageName=[[NSString alloc]initWithFormat:@"run%d.tiff",i];
UIImage *image=[UIImage imageNamed:imageName];
[mArray addObject:image];
[imageName release];
}
//爲imageView的動畫圖片數組賦值。
self.imageView.animationImages=mArray;
//設定事件,默認持續時間
self.imageView.animationDuration=3;
//播放動畫
[self.imageView startAnimating];
}
-(void)stopAction:(id)sender{
//動畫中止。
[self.imageView stopAnimating];
}
//加速控制UISlider的方法。
-(void)sliderAction:(id)sender{
UISlider *slider=(UISlider *)sender;
//判斷imageView動畫是否開始。
if ([self.imageView isAnimating]) {
[self.imageView stopAnimating];
self.imageView.animationDuration=slider.value;
[self.imageView startAnimating];
}
}
//10不一樣先畫畫,小鳥會走。
smallImage =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
smallImage.image=[UIImage imageNamed:@"鳥.png"];
[self addSubview:smallImage];
[smallImage release];
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(250, 320, 60, 40);
[button setTitle:@"走" forState:UIControlStateNormal];
[button addTarget:self action:@selector(doFlay) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
// [button release];//沒有初始化時候,release就沒有了。
// Initialization code
lineArray =[[NSMutableArray alloc]init];
colorArray=[[NSMutableArray alloc]init];
color=0;
//初始化兩個按鈕。
UIButton *btn1=[[UIButton alloc]initWithFrame:CGRectMake(250, 420, 70, 40)];
[btn1 setTitle:@"撤銷" forState:UIControlStateNormal];
[btn1 addTarget:self action:@selector(undo) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn1];
UIButton *btn2=[[UIButton alloc]initWithFrame:CGRectMake(20, 420, 70, 40)];
[btn2 setTitle:@"從新畫" forState:UIControlStateNormal];
[btn2 addTarget:self action:@selector(undoAll) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn2];
//初始化segment
NSArray *titles=[[NSArray alloc]initWithObjects:@"紅",@"綠",@"藍", nil];
UISegmentedControl *segment=[[UISegmentedControl alloc]initWithItems:titles];
segment.frame=CGRectMake(0, 380, 320, 40);
[segment addTarget:self action:@selector(segment:) forControlEvents:UIControlEventValueChanged];
[self addSubview:segment];
[segment release];
}
returnself;
}
- (void)drawRect:(CGRect)rect
{
//開始畫畫了。
context =UIGraphicsGetCurrentContext();
for (int i=0; i<[lineArray count]; i++) {
pointArray =[lineArray objectAtIndex:i];
if ([[colorArray objectAtIndex:i]intValue]==0) {
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
}
if ([[colorArray objectAtIndex:i]intValue]==1) {
CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
}
if ([[colorArray objectAtIndex:i]intValue]==2) {
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
}
CGContextSetLineWidth(context, 4.0f);
if ([pointArray count]>1) {
for (int j=0; j<[pointArray count]-1; j++) {
NSValue *a=[pointArray objectAtIndex:j];
CGPoint c=[a CGPointValue];
NSValue *b=[pointArray objectAtIndex:j+1];
CGPoint d=[b CGPointValue];
CGContextMoveToPoint(context, c.x, c.y);
CGContextAddLineToPoint(context, d.x, d.y);
}
}
CGContextStrokePath(context);
}
}
-(void)doFlay{//設置通過的點。也就是路徑。
CAKeyframeAnimation *animation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
// NSArray *values=[NSArray arrayWithObjects:[NSValue valueWithCGPoint:CGPointMake(100, 20)],[NSValue valueWithCGPoint:CGPointMake(40, 80)],[NSValue valueWithCGPoint:CGPointMake(30, 60)],[NSValue valueWithCGPoint:CGPointMake(20, 40)],[NSValue valueWithCGPoint:CGPointMake(0, 10)], nil];
NSArray *values=[NSArray arrayWithArray:pointArray];
[animation setValues:values];
[animation setDuration:4.0];
// [animation setDelegate:self];
// [bigImage.layer addAnimation:animation forKey:@"image-position"];
[smallImage.layer addAnimation:animation forKey:@"image-position"];
}
-(void)undo{
[lineArray removeLastObject];
[colorArray removeLastObject];
[self setNeedsDisplay];
}
-(void)undoAll{
[lineArray removeAllObjects];
[colorArray removeAllObjects];
[self setNeedsDisplay];
}
-(void)segment:(id)sender{
UISegmentedControl *tempSegment=(UISegmentedControl *)sender;
color=tempSegment.selectedSegmentIndex;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch=[touches anyObject];
firstPoint=[touch locationInView:self];
pointArray=[[NSMutableArray alloc]init];
[lineArray addObject:pointArray];
[colorArray addObject:[NSNumber numberWithInt:color]];
[pointArray release];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch=[touches anyObject];
lastPoint=[touch locationInView:self];
NSValue *value=[NSValue valueWithCGPoint:lastPoint];
pointArray =[lineArray lastObject];
[pointArray addObject:value];
// [self setNeedsDisplayInRect:CGRectMake(firstPoint.x, firstPoint.y, lastPoint.x-firstPoint.x, lastPoint.y-firstPoint.y)];
[self setNeedsDisplay];
}
//11唐老師最後一節課層動畫。
bigImage=[[UIImageView alloc]initWithFrame:CGRectMake(20, 20, 150, 250)];
NSString *str=[[NSBundle mainBundle]pathForResource:@"氣球" ofType:@"png"];
bigImage.image=[UIImage imageWithContentsOfFile:str];
[self.view addSubview:bigImage];
[bigImage release];
smallImage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 80, 30, 30)];
smallImage.image=[UIImage imageNamed:@"鳥.png"];
[bigImage addSubview:smallImage];
[smallImage release];
//layer
[bigImage.layer setCornerRadius:20];/////////圖上是綠矩形的角平滑度。
[bigImage.layer setShadowColor:[UIColor blackColor].CGColor];//陰影顏色。
//bigImage.layer.masksToBounds=YES;//給視圖添加註釋。和陰影不能一塊兒寫。
[bigImage.layer setShadowOffset:CGSizeMake(20, 20)];//設置陰影的起點位置
[bigImage.layer setShadowOpacity:0.5];//不透明度。0爲全透明。
[bigImage.layer setBorderColor:[UIColor greenColor].CGColor];
[bigImage.layer setBorderWidth:2];
//生成對應的十個按鈕。
for (int i=0; i<10; i++) {
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=i+1;
if (button.tag>7) {
button.frame=CGRectMake(15+80*(i-7), 415, 60, 40);
}
else{
button.frame=CGRectMake(255, 20+i*60, 60, 40);
}
[self.view addSubview:button];
}
NSArray *array=[NSArray arrayWithObjects:@"1",@"2", nil];
segmented=[[UISegmentedControl alloc]initWithItems:array];
segmented.frame=CGRectMake(30, 350, 100, 40);
[self.view addSubview:segmented];
[segmented release];
//分別給按鈕關聯方法。
UIButton *move=(UIButton *)[self.view viewWithTag:1];
[move setTitle:@"move" forState:UIControlStateNormal];
[move addTarget:self action:@selector(doChangeFrameToMove) forControlEvents:UIControlEventTouchUpInside];
//轉動。
UIButton *translate=(UIButton *)[self.view viewWithTag:2];
[translate setTitle:@"translate" forState:UIControlStateNormal];
[translate addTarget:self action:@selector(doTranslate) forControlEvents:UIControlEventTouchUpInside];
//旋轉。
UIButton *rotate=(UIButton *)[self.view viewWithTag:3];
[rotate setTitle:@"rotate" forState:UIControlStateNormal];
[rotate addTarget:self action:@selector(doRotate) forControlEvents:UIControlEventTouchUpInside];
//比例,規模。
UIButton *scale=(UIButton *)[self.view viewWithTag:4];
[scale setTitle:@"scale" forState:UIControlStateNormal];
[scale addTarget:self action:@selector(doScale) forControlEvents:UIControlEventTouchUpInside];
//轉化爲
UIButton *invert=(UIButton *)[self.view viewWithTag:5];
[invert setTitle:@"invert" forState:UIControlStateNormal];
[invert addTarget:self action:@selector(doInvert) forControlEvents:UIControlEventTouchUpInside];
//卷。
UIButton *curlUp=(UIButton *)[self.view viewWithTag:6];
[curlUp setTitle:@"curlUp" forState:UIControlStateNormal];
[curlUp addTarget:self action:@selector(doCurlUp) forControlEvents:UIControlEventTouchUpInside];
//輕擊,彈
UIButton *flip=(UIButton *)[self.view viewWithTag:7];
[flip setTitle:@"flip" forState:UIControlStateNormal];
[flip addTarget:self action:@selector(doFlip) forControlEvents:UIControlEventTouchUpInside];
//不透明。
UIButton *opacity=(UIButton *)[self.view viewWithTag:8];
[opacity setTitle:@"opacity" forState:UIControlStateNormal];
[opacity addTarget:self action:@selector(doOpacity) forControlEvents:UIControlEventTouchUpInside];
//花費
UIButton *expend=(UIButton *)[self.view viewWithTag:9];
[expend setTitle:@"expend" forState:UIControlStateNormal];
[expend addTarget:self action:@selector(doExpend) forControlEvents:UIControlEventTouchUpInside];
UIButton *flay=(UIButton *)[self.view viewWithTag:10];
[flay setTitle:@"flay" forState:UIControlStateNormal];
[flay addTarget:self action:@selector(doFlay) forControlEvents:UIControlEventTouchUpInside];
}
-(void)doChangeFrameToMove{
[UIView beginAnimations:nil context:nil];//第一個參數是動畫的標石,第二個參數是應用程序傳遞給動畫的代理的信息。一般不寫,
[UIView setAnimationDuration:2];//動畫持續時間。
// [UIView setAnimationDelegate:self];//設置動畫的回調函數,設置後可使用回調方法。也就 是代理方法。
// [UIView setAnimationDidStopSelector:@selector(a:)];//動畫完畢後調用的方法。「」不被新IOS版本支持。、
if (n==0) {
smallImage.frame=CGRectMake(130, 80, 30, 30);
n++;
}
else{
smallImage.frame = CGRectMake(0, 80, 30, 30);
n=0;
}
[UIView commitAnimations];
}
-(void)doTranslate
{
// NSLog(@"%s",__FUNCTION__);
CGAffineTransform transform;
if (segmented.selectedSegmentIndex==0) {
transform=CGAffineTransformTranslate(bigImage.transform, 10.0, 10.0);
}
else
{
transform=CGAffineTransformMakeTranslation(10.0, 10.0);
}
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.2];
[bigImage setTransform:transform];
[UIView commitAnimations];
}
-(void)doRotate{
NSLog(@"%s",__FUNCTION__);
CGAffineTransform transform;
if (segmented.selectedSegmentIndex==0) {
//根據目標對象當前的transform進行旋轉。
transform=CGAffineTransformRotate(bigImage.transform,M_PI/6.0);
}
else{
//根據原始位置旋轉。
transform=CGAffineTransformMakeRotation(M_PI/6.0);
}
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.2];
[bigImage setTransform:transform];
[UIView setAnimationDelegate:self];
// [UIView setAnimationDidStopSelector:@selector(animationAction)];
[UIView commitAnimations];
}
-(void)doScale{
NSLog(@"%s",__FUNCTION__);
CGAffineTransform transform;
if (segmented.selectedSegmentIndex==0) {
transform=CGAffineTransformScale(bigImage.transform,1.2,1.2);
}
else{
transform=CGAffineTransformMakeScale(1.2, 1.2);
}
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.2];
[bigImage setTransform:transform];
[UIView commitAnimations];
}
-(void)doInvert{
NSLog(@"%s",__FUNCTION__);
CGAffineTransform transform;
if (segmented.selectedSegmentIndex==0) {
transform=CGAffineTransformIdentity;
}
else{
transform=CGAffineTransformInvert(bigImage.transform);
}
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.2];
[bigImage setTransform:transform];
[UIView commitAnimations];
}
-(void)doCurlUp{
NSLog(@"%s",__FUNCTION__);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];//指定動畫曲線類型。淡入淡出。
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:bigImage cache:YES];//設置動畫的樣式,forview爲哪一個動畫實現這個效果。yes 時候陰影一塊兒走。
[UIView commitAnimations];
}
-(void)doFlip{
NSLog(@"%s",__FUNCTION__);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1];
if (m==0) {
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:bigImage cache:YES];
NSLog(@"xiang you");
m=1;
}
else{
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:bigImage cache:YES];
m=0;
NSLog(@"xiang zuo");
}
[UIView commitAnimations];
}
-(void)doOpacity{
NSLog(@"%s",__FUNCTION__);
//建立基本動畫。@裏的字符串有多種,必須寫對才行,這個是透明度。
CABasicAnimation *animation=[CABasicAnimation animationWithKeyPath:@"opacity"];//制定操做的屬性
//操做屬性的起始值;透明度的。
[animation setFromValue:[NSNumber numberWithFloat:1.0]];
//操做屬性的終點。
[animation setToValue: [NSNumber numberWithFloat:0.0]];
//動畫持續時間。
[animation setDuration:3.0];
//重複次數。
[animation setRepeatCount:3.0];
[animation setDelegate:self];
[animation setAutoreverses:YES];//默認的是NO即透明完畢後立馬恢復,YES是延遲恢復。
[bigImage.layer addAnimation:animation forKey:@"img-opacity"];//執行動畫。
}
-(void)doExpend{
CABasicAnimation *animation=[CABasicAnimation animationWithKeyPath:@"bounds.size"];
[animation setFromValue:[NSValue valueWithCGSize:CGSizeMake(1.0, 1.0)]];
[animation setToValue: [NSValue valueWithCGSize:bigImage.bounds.size]];//設置回原來的大小。
[animation setDuration:1.2];
[animation setDelegate:self];
[bigImage.layer addAnimation:animation forKey:@"image-bounds.size"];
}
-(void)doFlay{//設置通過的點。也就是路徑。
CAKeyframeAnimation *animation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
NSArray *values=[NSArray arrayWithObjects:[NSValue valueWithCGPoint:CGPointMake(100, 20)],[NSValue valueWithCGPoint:CGPointMake(40, 80)],[NSValue valueWithCGPoint:CGPointMake(30, 60)],[NSValue valueWithCGPoint:CGPointMake(20, 40)],[NSValue valueWithCGPoint:CGPointMake(0, 10)], nil];
[animation setValues:values];
[animation setDuration:1.0];
[animation setDelegate:self];
[bigImage.layer addAnimation:animation forKey:@"image-position"];
}
//動畫開始時調用。
-(void)animationDidStart:(CAAnimation *)anim{
NSLog(@"%s",__FUNCTION__);
}
//動畫結束時,他們都是自動調用,
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
NSLog(@"%s",__FUNCTION__);
if (flag) {
CAPropertyAnimation *propertAn=(CAPropertyAnimation *)anim;
[bigImage.layer removeAnimationForKey:propertAn.keyPath];
NSLog(@"keyPath=%@",propertAn.keyPath);
}
}
//指定動畫的代理對象,兩個代理方法的selector應該知足一下格式。、可是如今不容許用了。,
-(void)animationDidStop:(NSString *)animationId finished:(NSNumber *)finished context:(void*)context{
NSString *str=(NSString *)context;
if ([str isEqualToString:@"move"]) {
[smallImage setAlpha:0];
}
}