`
zjjzmw1
  • 浏览: 1352559 次
  • 性别: Icon_minigender_1
  • 来自: 开封
社区版块
存档分类
最新评论

iOS layer

    博客分类:
  • iOS
 
阅读更多

iOS layer

 //捏合手势方法。

-(void)pinchAction:(id)sender{

    NSLog(@"捏合");

    UIPinchGestureRecognizer *pin=(UIPinchGestureRecognizer *)sender;

//    self.myImageV.transform=CGAffineTransformMakeScale(pin.scale, pin.scale);

    pin.view.transform = CGAffineTransformScale(pin.view.transform, pin.scale, pin.scale);

    pin.scale = 1;

    

    float tempF = self.myImageV.size.height/self.myImageV.size.width;

    if (self.myImageV.size.width<150) {

        self.myImageV.size = CGSizeMake(150, 150*tempF);

    }

    

}

 

#if 0

//1iOS-CALayer的最简单使用

iOSCore 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"];

 

这里使用了setTypesetSubtype组合,这使用个比较保险,因为他的参数就是官方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,cacheYES的时候比较高效,但是动画过程中不能更新界面上的内容,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 (^)(BOOL finished))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 (^)(BOOL finished))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)

{

 

}];

 

areAnimationsEnabledNO,上面不能动画显示

 

 

[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:self action:@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{

//循环生成28view

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:self action:@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:self action:@selector(rotationAction:)];

rotation.rotation=9;//旋转的弧度。

[self.imageView addGestureRecognizer:rotation];

[rotation release];

}

break;

case 4:

{

//捏合。

UIPinchGestureRecognizer *pinch=[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchAction:)];

[self.imageView addGestureRecognizer:pinch];

[pinch release];

}

break;

case 5:

{

//拖拽。

UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@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];

}

}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics