이미지 뷰의 애니메이션 이미지 뷰는 자체적으로 애니메이션 기능을 제공하고 있습니다.

Slides:



Advertisements
Similar presentations
Lecture 3 - Writing Initializers A correct initializer must comply with the following: The initializer name should begin with init The initializer returns.
Advertisements

Table Views UITableView. Overview Table view basics Tables display lists of data Each item in a tables list is a row Tables can have an unlimited number.
IOS – Views and Drawing CS4521. Views Rectangular area on screen Draws content Handles events Subclass of UIResponder (event handling class) Views arranged.
suppose you had Bumblebee, Jet, and Bird classes. All three, although unrelated, implement the flying behavior, and so you could say they are each a Flyer.
Detecting Collisions CSE 391 Fall 2012 Tony Scarlatos.
Animation Pre-Lab Lecture 3 1. Revisit 2  Pre-Lab 2  Create new UI components through codes  Too many UI components that are required to put on the.
The First Program. Step 1  File->New Project Create a project named “HelloWorld”, and select View Based Application from the icons on the right.
The Accelerometer CSE 391 Fall 2011 Tony Scarlatos.
Other Input Methods Pre-Lab Lecture 4 1. Revisit 2  Pre-Lab 3 – Animation  Boundary Information  Layer Concept  Animation algorithm  Next Position.
Objective-C Foundation Lecture 2 1. Flows of Lecture 2  Before Lab  Introduction to Objective-C  Intrinsic Variable  Flow Control  Class vs. Object.
Anatomy of an iPhone Application Content taken from book: “iPhone SDK Development” by Bill Dudney and Chris Adamson.
IPhone Development Crash Course By Dylan Harris
IPhone Development JaxCodeCamp Who am I David Fekke.NET Developer, ColdFusion Work at LPS Presenter JaxDug, JaxJug, JSUG & JaxFusion Mac User 1986.
IPhone 101. Outline Objective-C Random bits of the API Using the simulator Debugging with Xcode.
IStarted- And You Can Too! A Beginner’s Guide to iOS Programming.
Storyboards Managing multiple views. Overview Create a single view application Give the project a name and click “Use Storyboards” and “Use Automatic.
Objective-C for C# and Java Developers JaxCodeCamp 2012.
Memory Management and Automatic Reference Counting/ Copying Objects Archiving Copyright © 2012 by Yong-Gu Lee
Sprite Animation CSE 391 Fall 2012 Tony Scarlatos.
IOS WorkShoP Xcode 4 iOS 5 : “A Primer”. Objective-C iOS applications are written in Objective-C language using the Cocoa Touch library Objective-C is.
Simple Game Animation – iPhone Programming Exercise 3 CSE 391 Fall 2012 Tony Scarlatos.
Refactoring Moving a console app to a UI app. Refactoring Goal: change a console app to a UI app Principles: The main.m goes away The local variables.
IPhone Programming Version 2 Created by Nathan Magnus.
iOS components in Swift
1 Designing with a UIToolBar iPhone/iPad, iOS Development Tutorial.
Tabbed Views UITabBarController. Controller Architecture UITabBarController Controls the first view that the user sees The view controller class (and.
Navigation in iPads splitViewController. Overview Create a Master-Detail application Switch Device Family to iPad Give the project a name and click “Use.
Managing Multiple Views and Segues FA 172 Intro to Mobile App Development.
Create a Web View App Step-by-Step. Step 1 Create a new project in XCode using the "Single View Application" option.
Objective C. Основан на C Объектно-ориентированный Использует сообщения Динамический Протоколы Интроспекция.
View Controllers Content taken from book: “iPhone SDK Development” by Bill Dudney and Chris Adamson.
Gestures UIGestureRecognizer.
Passing data between storyboard views Singleton pattern.
E-MENU DEV. DOC Created: 3 Oct 2013 Created: Traitet Th. Modified: 3 Oct 2013 Modified: Traitet Th. Website:
Introduction to Objective-C and Xcode (Part 5) FA 175 Intro to Mobile App Development.
Course Summary Xcode & iPhone Simulator
Sounds, Images, and Text FA 172 Intro to Mobile App Development.
Sprites Actions/Particles/Sound Revisit the 'flying saucer' sprite: Again add it to the game Implement Chipmunk Physics collision feedback with missiles.
IPhone Programming Version 2 Created by Nathan Magnus.
Ios7 系列视频教程 主讲老师:廖珑程 邮箱地址: Sprite Kit 与 cocos 2d 的对比 内嵌入 ios 系统中 很好的支持纹理和粒子效果 很多其他引擎无法做到的事情,(视 频) 可移植性不好 对 OPENGL 的支持不好.
The Controller in MVC of iOS CS4521. The controller in the MVC  Controller  Knows about model and view objects  The brains of the operation  Manages.
Persistence CS 344 Mobile App Development Robert Muller.
1 UI Alert View iPhone/iPad, iOS Development Tutorial.
Simple Scene Management a layer has the size of the device screen it defines appearance and behavior a scene is composed of one or more layers app transitions.
1 Group: IK0804 Supervisor: Prof. KING Kuo Chin, Irwin Member: Ng Hon Pan (s ) Wong Hung Ki(s )
More Objective-C Details FA 172 Intro to Mobile App Development.
Objective-C 기초 2 DongJoo Kim. Instagram Initial Release Users - 10 Million ( in 355days) Funding - 약 80 억원 기업가치 억원 ( 추정 )
The iOS Platform and SDK. iOS iPhoneiPad Mini iPad.
OBJECTIVE C Kurt Ladendorf. General Knowledge  Super set of C  Smalltalk  Mainly used for iOS and other Apple development.
IOS Programming Medialogy, Semester 7, 2010 Aalborg University, Aalborg David Meredith
Introduction to Objective-C and Xcode (Part 4) FA 175 Intro to Mobile App Development.
2010/12/16 朱中華.  這個程式會先在 iPhone 螢幕上顯示 This is the Front View 及箭頭, click 任何地方後, 畫面會翻轉 (transition) 至下個畫面 ---This is the Back View 及箭頭,每次 click ,交替出 現,見下圖。
1 디바이스 정보  UIDevice 클래스가 제공하고 static 메서드인 currentDevice 가 객체를 생성합 니다.  제공하는 정보 uniqueIdentifier: 장치 고유 ID / 회원가입을 하지 않고 어플을 운영 가능 model: 모델명 systemVersion:
수업 진행 UINavigationController ( 목 ) Animation ( 목 ) TabBarViewController ( 목 ) UITableViewController ( 금 ) CoreLocation ( 토 )
Drawing And Animations
iStarted- And You Can Too!
Control Circle Project Revisited
Akinori Ito, *Kengo Watanabe Genki Kuroda, Ken’ichiro Ito
Designing with Introspection
What is UI Element in iPhone Development?
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
CSC 581: Mobile App Development
Presentation transcript:

이미지 뷰의 애니메이션 이미지 뷰는 자체적으로 애니메이션 기능을 제공하고 있습니다. animationImages 프로퍼티에 UIImage 타입의 배열을 대입하고 startAnimating 메서드를 호출하면 됩니다. isAnimating은 애니메이션 실행여부를 리턴 stopAnimating 메서드로 애니메이션을 중지 시킬 수 있으며 animationRepeatCount로 애니메이션의 반복횟수를 설정할 수 있으며 animationDuration으로 애니메이션 간격을 조정할 수 있습니다. 1

UIView Animation 뷰에 적용할 수 있는 애니메이션 효과 위치 변화 및 크기 변화 및 투명도 변화와 회전 등이 가능 애니메이션의 설정의 시작과 종료에 사용되는 메서드 +(void)beginAnimations:(NSString *)animationID context:(void *)context +(void)commitAnimations 위의 2개의 메서드 사이에 이용하고자 하는 애니메이션 효과를 지정 타이머를 이용해서 호출하게 되면 조금 더 다양한 애니메이션이 가능 애니메이션을 적용할 수 있는 뷰의 속성 frame: 슈퍼 뷰에서의 뷰의 프레임 bounds: 뷰 좌표계에서의 뷰의 프레임 center: 슈퍼 뷰 좌표계에서의 프레임의 중심 alpha: 뷰의 투명도 backgroundColor hidden opacity transform 2

+(void)setAnimationStartDate:(NSDate *)startTime:애니메이션 시작 시간 뷰 애니메이션 설정에 이용되는 메서드 +(void)setAnimationStartDate:(NSDate *)startTime:애니메이션 시작 시간 +(void)setAnimationDelay:(NSTimeInterval)delay:애니메이션 지연 시간 +(void)setAnimationRepeatCount:(float)repeatCount:반복 횟수 +(void)setAnimationRepeatAutoreverses:(BOOL)repeatAutoreverses:반복효과 +(void)setAnimationCurve:(UIViewAnimation)curve:가속과 감속 곡선을 정의 +(void)setAnimationDuration:(NSTimeInterval)duration:애니메이션 시간 3

화면 전환 효과 만들기 플립(화면 전환) 효과를 만들기 위해서는 UIView 애니메이션 블럭안에서 setAnimationTransition 메서드를 호출하여 어떤 변환을 수행할 것인지를 주면 됩니다. [UIView setAnimationTransition: 화면전환효과 forView:적용될 뷰 객체 cache:캐시 사용 여부]; 화면 전환 효과에 사용되는 값 UIViewAnimationTransitionCurlDown UIViewAnimationTransitionCurlUp UIViewAnimationTransitionFlipFromLeft UIViewAnimationTransitionFlipFromRight UIViewAnimationTransitionNone 4

UIView Animation Delegate 애니메이션 수행 전 후에 다른 메서드를 호출하고자 하는 경우에는 아래의 메 서드들을 이용합니다. + setAnimationDelegate: => 아래 2개의 메서드가 구현된 객체 지정 + setAnimationWillStartSelector: => 애니메이션이 시작되기 전에 호출될 메서드 지정 + setAnimationDidStopSelector: => 하나의 애니메이션이 종료된 후 호출되는 메서드 지정 5

타이머 애니메이션 6

1.Single View Application 프로젝트 생성(TimerAnimation) 2.1개의 이미지 파일을 프로젝트에 추가(ball.png) 3.ViewController.h 파일에 변수(ball.png 파일을 UIImage 객체로 저장할 변수) 선언 #import <UIKit/UIKit.h> @interface ViewController : UIViewController { UIImage * image; } @end 4.ViewController.m 파일에 viewDidLoad 메서드 수정 (ball.png 파일을 image에 연결하고 0.1초마다 현재 클래스에 선언된 timerProc: 메서드를 무한 반복하는 타이머를 생성) - (void)viewDidLoad [super viewDidLoad]; image = [UIImage imageNamed:@"ball.png"]; [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerProc:) userInfo:nil repeats:YES]; 7

5.ViewController.m 파일에 timerProc: 메서드 구현 (UIImageView 객체를 생성해서 애니메이션을 적용) -(void)timerProc:(NSTimer *)timer { UIImageView * imgView = [[UIImageView alloc]initWithImage:image]; int startPoint = ((int)random() % (int)([[UIScreen mainScreen]bounds].size.width)); int endPoint = ((int)random() % (int)([[UIScreen mainScreen]bounds].size.width)); double scale = 1 / (int)random() % 100 + 1.0; double speed = 1 / (int)random() % 100 + 1.0; imgView.frame = CGRectMake(startPoint, -50, 25, 25*scale); imgView.alpha = 0.5; [self.view addSubview:imgView]; [imgView release]; [UIView beginAnimations:nil context:imgView]; [UIView setAnimationDuration:5 * speed]; [UIView setAnimationDidStopSelector:@selector(animationDidStop: finished: context:)]; [UIView setAnimationDelegate:self]; imgView.frame = CGRectMake(endPoint, [[UIScreen mainScreen]bounds].size.height, 25, 25*scale); [UIView commitAnimations]; } 6.ViewController.m 파일에 애니메이션 종료 후 호출되는 메서드 구현 (부가 정보를 이용해서 넘어온 뷰를 부모 뷰로부터 제거) -(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context UIImageView * imsi = context; [imsi removeFromSuperview]; 8

Layer 코어 애니메이션의 랜더링 평면으로 직접적인 출력은 안되고 UIView에 포함되서 출력됩니다. 뷰에는 기본적으로 CALayer 타입으로 1개의 레이어가 포함되어 있습니다. 레이어 조작은 QuartzCore 프레임워크를 이용합니다. 레이어의 종류 CALayer: 일반 레이어 CAGradientLayer: 여러가지 색상을 적용해서 출력하는 레이어 CATiledLayer: 레이어를 분할해서 출력할 수 있는 레이어 CAEAGLLayer: OpenGL ES에서 사용하는 레이어 CALayer를 제외한 Layer를 사용하고자 하는 경우에 View클래스에서 +(class)layerClass라는 메서드를 재정의 해서 사용하고자 하는 Layer의 class를 리턴해야 합니다. 9

CALayer의 멤버 레이어 생성 Layer 속성 계층 관련 속성과 메서드 + layer – init – initWithLayer: Layer 속성 frame bounds position zPosition   anchorPoint - 기본적으로 0.5, 0.5 입니다. transform => CATransform3DMake? 메서드로 조작하며 회전은 각도와 3개의 축에 적용할 값을 매개변수로 대입 opaque   opacity   hidden   backgroundColor   shadowOpacity   shadowRadius   shadowOffset   shadowColor   계층 관련 속성과 메서드 sublayers   superlayer   – addSublayer: – removeFromSuperlayer – insertSublayer:atIndex: – insertSublayer:below: – insertSublayer:above: – replaceSublayer:with: 10

레이어를 이용한 뷰 애니메이션 11

1.Single View Application 프로젝트 생성(LayerAni) 2.1개의 이미지 파일을 프로젝트에 추가(Arrow.png) 3.프로젝트에 QuartzCore(레이어 조작을 위한 프레임워크) 프레임워크 추가 4.ViewController.h 파일에 변수 선언 (이미지를 표시할 이미지 뷰와 이미지 전환에 이용할 변수) #import <UIKit/UIKit.h> @interface ViewController : UIViewController { UIImageView * imgView; BOOL flag; } @end 5.ViewController.m 파일에 헤더파일을 import #import <QuartzCore/QuartzCore.h> 6.ViewController.m 파일에 viewDidLoad 메서드 수정 (UIImageView 객체를 생성해서 이미지를 연결) - (void)viewDidLoad [super viewDidLoad]; imgView = [[UIImageView alloc]initWithFrame:CGRectMake(100,100, 23,60)]; imgView.image = [UIImage imageNamed:@"Arrow.png"]; [self.view addSubview:imgView]; [imgView release]; 12

7.ViewController.m 파일에 -(void)touchesBegan 메서드 구현 (터치할 때마다 0.3초마다 z축으로 180도 회전하는 애니메이션을 적용) -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if(!flag) [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDelegate:self]; [UIView setAnimationDuration:0.3]; [imgView layer].transform = CATransform3DMakeRotation(M_PI, 0, 0, 1); [UIView commitAnimations]; } else [imgView layer].transform = CATransform3DMakeRotation(M_PI*2, 0, 0, 1); flag = !flag; 13

반사 효과 뷰의 레이어를 복사해서 새로운 레이어를 만든 후 크기를 y축으로 음수를 적용해서 변경한 후 좌표이동을 수행하고 이 레이어를 뷰에 추가해주면 됩니다. 여기에 opacity를 적절히 조절하여 색상을 조절하면 됩니다. 14

반사효과 15

1.이전 프로젝트에 1개의 이미지 파일을 프로젝트에 추가(소녀시대.jpg) 2.ViewController.h 파일에 변수 추가(이미지를 출력할 이미지 뷰 변수 선언) UIImageView * mirrorView; 3.ViewController.m 파일의 viewDidLoad 메서드에 추가 (이미지 뷰 객체를 생성하고 레이어를 복사해서 반사 효과를 적용) - (void)viewDidLoad { [super viewDidLoad]; imgView = [[UIImageView alloc]initWithFrame:CGRectMake(100,100, 23,60)]; imgView.image = [UIImage imageNamed:@"Arrow.png"]; [self.view addSubview:imgView]; [imgView release]; mirrorView = [[UIImageView alloc]initWithFrame:CGRectMake(150,100, 150,150)]; mirrorView.image = [UIImage imageNamed:@"소녀시대.jpg"]; [self.view addSubview:mirrorView]; CALayer *copyLayer = [CALayer layer]; copyLayer.contents = [mirrorView layer].contents; copyLayer.opacity = 0.5; copyLayer.frame = CGRectMake(0.0f, 0.0f, mirrorView.frame.size.width, mirrorView.frame.size.height * -0.5); CATransform3D stransform = CATransform3DMakeScale(1.0f, -1.0f, 1.0f); CATransform3D transform = CATransform3DTranslate(stransform, 0.0f, -(75 + mirrorView.frame.size.height), 0.0f); copyLayer.transform = transform; copyLayer.sublayerTransform = copyLayer.transform; [[mirrorView layer] addSublayer:copyLayer]; [mirrorView release]; } 16

CABasicAnimation 레이어의 속성 변화 애니메이션에 사용되는 클래스 생성 [CABasicAnimation animationWithKeyPath:keyPath] keyPath에 변화시키고자 하는 속성을 문자열로 입력 frame은 안됩니다. fromValue와 toValue 사이의 보간법으로 애니메이션 적용 fromValue:시작 값 – NSValue 타입으로 설정 toValue: 종료 값 – NSValue 타입으로 설정 duration: 적용 시간 timingFunction: 가속과 감속 옵션 delegate: 적용 객체 autoreverses: 반복 여부 적용 [layer객체 addAnimation:CABasicAnimation객체 forKey: @”구별하는 이름”] 17

Basic Animation 18

1.Single View Application 프로젝트 생성(AttributeAnimation) 2.프로젝트에 이미지 파일 추가(image.png) 3.프로젝트에 QuartzCore.framework(Layer관련 기능) 링크 추가 4.ViewController.h 파일에 프로퍼티 선언(애니메이션을 적용할 이미지 뷰 변수를 프로퍼티로 선언) #import <UIKit/UIKit.h> @interface ViewController : UIViewController @property(nonatomic, retain) UIImageView * imgView; @end 19

5.ViewController.xib 파일의 view에 버튼1개를 배치하고 메서드 연결 메서드는 BasicAnimation 20

6.ViewController.m 파일에 헤더파일 import #import <QuartzCore/QuartzCore.h> 7.ViewController.m 파일에 synthesize 구현 @synthesize imgView; 8.ViewController.m 파일에 viewDidLoad 메서드 수정(imgView를 생성해서 출력) - (void)viewDidLoad { [super viewDidLoad]; //imgView를 생성해서 뷰 위에 추가 imgView = [[UIImageView alloc]initWithFrame:CGRectMake(50,50,100,100)]; imgView.image = [UIImage imageNamed:@"image.png"]; [self.view addSubview:imgView]; } 21

9.ViewController.m 파일에 BasicAnimation 메서드 구현 (position에 변화를 주는 BasicAnimation 적용) -(IBAction)BasicAnimation { //position에 변화를 주는 애니메이션 생성 CABasicAnimation * ani = [CABasicAnimation animationWithKeyPath:@"position"]; //애니메이션 시작 값과 종료 값을 설정 //값은 NSValue나 NSNumber 타입으로 설정 - key에 따라 다름 ani.fromValue = [NSValue valueWithCGPoint:CGPointMake(100, 100)]; ani.toValue = [NSValue valueWithCGPoint:CGPointMake(200, 200)]; ani.duration = 3.0; //인터폴레이션 효과 ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; ani.delegate = self; //자동 반복 효과 설정 ani.autoreverses = YES; //imgView의 layer에 ani를 적용 [imgView.layer addAnimation:ani forKey:nil]; imgView.layer.position = CGPointMake(100, 100); } 10.ViewController.m 파일의 dealloc 메서드 재정의 - (void)dealloc [imgView release]; [super dealloc]; 22

CAKeyframeAnimation Keyframe은 중간에 인터폴레이션이 이루어지는 참조 포인트 애니메이션을 세밀하게 적용시키고자 하는 경우 사용하는 클래스 생성: [CAKeyframeAnimation animationWithKeyPath:@"키이름"]; 정확하게 원하는 시간에 원하는 속성의 변화를 적용하기 위한 애니메이션 values와 keyTimes에 값을 NSArray *로 적용하면 됩니다. calcurationMode: 보정 적용 방법 path: 2개의 값을 가진(Dual Value – CGPoint, CGSize...)를 설정할 수 있는 속성으로 CGPathRef 타입으로 지정합니다. 경로를 설정할 때는 CGPathRef나 CGMutablePathRef 타입의 변수를 CGPathCreateMutable() 메서드를 호출해서 생성하고 CGPathMoveToPoint(), CGPathAddLineToPoint()를 이용해서 경로를 추가한 후 CGPathCloseSubpath()를 이용해서 경로 설정을 종료하면 됩니다. CGPathAddCurveToPoint() 메서드를 이용해서 Path에 추가할 수 도 있습니다. CGPathRef나 CGMutablePathRef 변수는 CFRelease 함수를 이용해서 메모리 정리를 수행합니다. 23

1. 이전 프로젝트의 ViewController 1.이전 프로젝트의 ViewController.xib 파일의 view에 버튼1개를 추가하고 메서드 연결(KeyframeAnimation) 24

2.ViewController.m 파일에 메서드 구현 -(IBAction)KeyframeAnimation { CAKeyframeAnimation *ani = [CAKeyframeAnimation animationWithKeyPath:@"position"]; ani.calculationMode = kCAAnimationPaced; ani.values = [NSArray arrayWithObjects:[NSValue valueWithCGPoint:CGPointMake(100,100)],[NSValue valueWithCGPoint:CGPointMake(200,400)],[NSValue valueWithCGPoint:CGPointMake(100,100)], nil]; ani.keyTimes = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],[NSNumber numberWithFloat:12.0], [NSNumber numberWithFloat:20.0], nil]; ani.duration = 23.0; ani.delegate = self; [imgView.layer addAnimation:ani forKey:nil]; } 25

ViewController.m 파일에 메서드 수정 -(IBAction)KeyframeAnimation { CAKeyframeAnimation *ani = [CAKeyframeAnimation animationWithKeyPath:@"position"]; CGMutablePathRef thePath = CGPathCreateMutable(); CGPathMoveToPoint(thePath,NULL, 100,100); CGPathAddLineToPoint(thePath, NULL, 200, 200); CGPathAddLineToPoint(thePath, NULL, 200, 350); CGPathAddLineToPoint(thePath, NULL, 50, 350); CGPathAddLineToPoint(thePath, NULL, 50, 200); CGPathCloseSubpath(thePath); ani.path = thePath; ani.calculationMode = kCAAnimationPaced; ani.duration = 3.0; ani.delegate = self; [imgView.layer addAnimation:ani forKey:nil]; CFRelease(thePath); imgView.frame = CGRectMake(50, 50, 100, 100); } 26

ViewController.m 파일에 메서드 수정 -(IBAction)KeyframeAnimation { CAKeyframeAnimation *ani = [CAKeyframeAnimation animationWithKeyPath:@"position"]; CGMutablePathRef thePath = CGPathCreateMutable(); CGPathMoveToPoint(thePath,NULL, 50,200); CGPathAddCurveToPoint(thePath,NULL,100.0,20.0, 220.0,350.0,270.0,200.0); ani.path = thePath; ani.calculationMode = kCAAnimationPaced; ani.duration = 3.0; ani.delegate = self; [imgView.layer addAnimation:ani forKey:nil]; CFRelease(thePath); imgView.frame = CGRectMake(220, 150, 100, 100); } 27

CAGroupAnimation 2개 이상의 애니메이션을 적용하고자 하는 경우 사용하는 클래스 생성 [CAAnimationGroup animation]; 애니메이션 추가는 animations 속성에 애니메이션 들을 배열로 만들어서 대입 레이어에 적용할 때는 addAnimation: forKey: 메서드 이용 28

1. 이전 프로젝트의 ViewController 1.이전 프로젝트의 ViewController.xib 파일의 view에 버튼1개를 배치하고 메서드 연결(GroupAnimation) 29

2.ViewController.m 파일에 메서드 구현 -(IBAction)GroupAnimation { CAKeyframeAnimation *curve = [CAKeyframeAnimation animationWithKeyPath:@"position"]; CGMutablePathRef thePath = CGPathCreateMutable(); CGPathMoveToPoint(thePath,NULL, 50,200); CGPathAddCurveToPoint(thePath,NULL,100.0,20.0, 220.0,350.0,270.0,200.0); curve.path = thePath; curve.calculationMode = kCAAnimationPaced; curve.duration = 12.0; curve.delegate = self; [imgView.layer addAnimation:curve forKey:nil]; CFRelease(thePath); imgView.frame = CGRectMake(220, 150, 100, 100); CAKeyframeAnimation *opacity = [CAKeyframeAnimation animationWithKeyPath:@"opacity"]; opacity.calculationMode = kCAAnimationPaced; opacity.values = [NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:0.75], [NSNumber numberWithFloat:0.0], nil]; opacity.keyTimes = [NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:4.0], [NSNumber numberWithFloat:12.0], nil]; CAAnimationGroup *group = [CAAnimationGroup animation]; group.duration = 12.0; group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; group.animations = [NSArray arrayWithObjects:opacity, curve, nil]; [imgView.layer addAnimation:group forKey:@"animate"]; } 30

CATransition CATransition를 이용하면 화면 전환 애니메이션을 만들 수 있습니다. CATransition *객체 = [CATransition animation]로 객체를 생성해서 kCATransition효과 중 하나를 type 프로퍼티에 지정하면 됩니다. type(효과)에 따라 subType(방향)도 있습니다. kCATransitionFade: 서서히 사라지는 효과로 subType 없음 kCATransitionMoveIn: 레이어가 미끄러지듯이 나옴 (subType으로 kCATransitionFrom방향을 지정할 수 있음) kCATransitionPush: 레이어의 내용물을 밀어내는 효과로 subType 지정 가능 kCATransitionReveal: 천천히 레이어의 내용물이 나타나는 효과로 subType 지정 가능 31

CATransition 효과 32

1.Empty Application 프로젝트 생성(TransitionTest) 2.2개의 이미지를 리소스 폴더에 복사(image1.png, image2.png) 3.프로젝트에 레이어 애니메이션을 사용하기 위해 QuartzCore.framework 링크 추가 4.애니메이션을 적용할 UIView로 부터 상속받는 MyView 클래스 생성 33

5.MyView.h파일에 헤더파일(화면전환 애니메이션 사용)을 import하고 화면전환에 이용할 2개의 이미지 뷰와 flag 변수 선언 #import <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> @interface MyView : UIView { UIImageView *frontView; UIImageView *backView; int flag; } @end 6.MyView.m 파일에 initWithFrame 재정의 - 2개의 이미지 뷰 객체를 생성하고 배치 - (id)initWithFrame:(CGRect)frame self = [super initWithFrame:frame]; if (self) frontView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [frontView setImage:[UIImage imageNamed:@"image1.png"]]; backView = [[UIImageView alloc]initWithFrame:[[UIScreen mainScreen] bounds]]; [backView setImage:[UIImage imageNamed:@"image2.png"]]; [self addSubview:backView]; [self addSubview:frontView]; flag = 0; [backView release]; [frontView release]; return self; 34

7.MyView.m 파일에 터치 메서드 재정의 - 이미지 뷰를 교체하면서 화면 전환 효과 애니메이션 적용 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CATransition *animation = [CATransition animation]; [animation setDelegate:self]; [animation setDuration:1.0f]; [animation setTimingFunction:UIViewAnimationCurveEaseInOut]; [animation setType:kCATransitionFade]; /* [animation setType:kCATransitionMoveIn]; [animation setSubtype:kCATransitionFromTop]; */ if(!flag) [self sendSubviewToBack:frontView]; } else [self sendSubviewToBack:backView]; flag = !flag; [[self layer] addAnimation:animation forKey:@"transitionViewAnimation"]; 35

8.AppDelegate.m 파일의 application: didFinishLaunchingWithOptions 메서드 수정 (MyView 객체를 생성해서 window 위에 추가) #import "MyView.h" - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { MyView *flipView = [[MyView alloc] initWithFrame:[[UIScreen mainScreen]bounds]]; [self.window setBackgroundColor:[UIColor blackColor]]; [self.window addSubview:flipView]; [flipView release]; [self.window makeKeyAndVisible]; return YES; } 36

CATransition의 비공개 애니메이션 type에 Document에는 없는 애니메이션을 적용할 수 있습니다. 문자열로 type에 지정하면 됩니다. cameralris: 카메라 셔터, cameraIrisHollowClose, cameraIrisHollowOpen cube: 육면체 oglFlip: 반전 pageCurl: 페이지 넘기기 pageUnCurl: 페이지 되돌리기 rippleEffect: 물결무늬 suckEffect: 흡입 효과 37

CATransition 비공개 효과 예제 38

1.Single View Application 프로젝트 생성(HideTransition) 2.2개의 이미지를 복사(image1.png, image2.png) 3.프로젝트에 QuartzCore.framework 링크 추가 4.ViewController.h 파일에 헤더파일 import #import <QuartzCore/QuartzCore.h> 5.ViewController.h 파일에 변수와 메서드 선언 (애니메이션 효과와 방향을 설정할 변수와 출력할 이미지 뷰를 결정할 변수) @interface ViewController : UIViewController { NSString * type; NSString * subType; BOOL flag; } @end 39

6.ViewController.xib 파일에 2개의 ImageView를 배치하고 변수(imgView1, imgView2)를 연결하고 기본 이미지를 image1.png와 image2.png를 연결 세그먼티드 컨트롤을 2개 배치하고 IBAction 메서드(typeChange,subTypeChange)를 valueChanged 이벤트에 연결 40

7.ViewController.m 파일에 viewDidLoad 메서드 수정 (이미지 뷰의 출력 좌표를 설정하고 터치를 받을 수 있도록 설정하고 imgView1을 화면에 출력) - (void)viewDidLoad { [super viewDidLoad]; type = @"cameralris"; subType = kCATransitionFromRight; imgView1.center = self.view.center; imgView2.center = self.view.center; imgView1.userInteractionEnabled = YES; imgView2.userInteractionEnabled = YES; [self.view addSubview:imgView1]; } 8.ViewController.m 파일에 -(IBAction)subTypeChange:(id)sender 메서드 구현 (세그먼티드 컨트롤의 선택된 인덱스를 이용해서 subType을 설정) -(IBAction)subTypeChange:(id)sender int sel = [sender selectedSegmentIndex]; switch(sel) case 0: subType = kCATransitionFromRight; break; case 1: subType = kCATransitionFromLeft; case 2: subType = kCATransitionFromTop; case 3: subType = kCATransitionFromBottom; 41

9.ViewController.m 파일에 -(IBAction)typeChange:(id)sender 메서드 구현 { int sel = [sender selectedSegmentIndex]; switch(sel) case 0: type = @"cameralris"; break; case 1: type = @"cube"; case 2: type = @"oglFlip"; case 3: type = @"pageCurl"; case 4: type = @"pageUnCurl"; case 5: type = @"rippleEffect"; case 6: type = @"suckEffect"; } 42

10.ViewController.m 파일에 터치 메서드 구현 (터치를 시작하면 이미지 뷰를 교체하고 애니메이션을 적용) -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CATransition *animation = [CATransition animation]; [animation setDelegate:self]; [animation setDuration:1.0f]; [animation setTimingFunction:UIViewAnimationCurveEaseInOut]; [animation setType:type]; [animation setSubtype:subType]; if(!flag) [imgView1 removeFromSuperview]; [self.view addSubview:imgView2]; } else [imgView2 removeFromSuperview]; [self.view addSubview:imgView1]; [[self.view layer] addAnimation:animation forKey:@"transitionViewAnimation"]; flag = !flag; 43

Core Animation 활용 44

1.Single View Application 프로젝트 생성(CoreAnimation) 2.3개의 이미지를 리소스 폴더에 복사(Background.png, Photo.jpg, Box.jpg) 3.프로젝트에 QuartzCore.framework 링크 추가 4.UIView로 부터 상속받는 MainView 클래스 생성 5.ViewController의 view의 클래스를 MainView로 변경 45

6.View에 문자열을 출력할 수 있는 클래스를 생성 (NSObject로 부터 상속받는 TrayLabelDelegate 클래스를 생성) 7.TrayLabelDelegate.m 파일에 헤더파일 import #import <QuartzCore/QuartzCore.h> 8.TrayLabelDelegate.m 파일에 메서드 구현 - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { NSString *text = [layer valueForKey:@"text"]; CGFloat fontSize = 0.75f * CGRectGetHeight(layer.bounds); UIFont *font = [UIFont boldSystemFontOfSize:fontSize]; UIGraphicsPushContext(ctx); CGSize textSize = [text sizeWithFont:font]; CGPoint textPoint; textPoint.x = 0.5f * (CGRectGetWidth(layer.bounds) - textSize.width); textPoint.y = 0.5f * (CGRectGetHeight(layer.bounds) - textSize.height); [[UIColor whiteColor] setFill]; UIRectFill(layer.bounds); [[UIColor blackColor] setStroke]; UIRectFrame(layer.bounds); [[UIColor blackColor] setFill]; [text drawAtPoint:textPoint withFont:font]; UIGraphicsPopContext(); } 46

9.MainView.h 파일에 헤더파일 import와 변수 선언 #import <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> #import "TrayLabelDelegate.h" @interface MainView : UIView { CALayer * mainLayer; CALayer *inTrayLayer; CALayer *outTrayLayer; CALayer *photoRootLayer; TrayLabelDelegate *trayLabelDelegate; CALayer *dragLayer; CGPoint dragOrigin; } @end 10.MainView.m 파일에 이름없는 카테고리를 생성 @interface MainView () - (CALayer *)createTrayWithLabel:(NSString *)label; 47

11.MainView.m 파일에 createTrayWithLabel: 메서드 구현 - (CALayer *)createTrayWithLabel:(NSString *)label { CALayer *trayLayer = [CALayer layer]; trayLayer.bounds = CGRectMake(0, 0, 80, 100); trayLayer.contents = (id)[[UIImage imageNamed:@"Box.jpg"] CGImage]; [mainLayer addSublayer:trayLayer]; CALayer *labelLayer = [CALayer layer]; labelLayer.bounds = CGRectMake(0, 0, 40, 16); labelLayer.position = CGPointMake(40, 100); labelLayer.delegate = trayLabelDelegate; [labelLayer setNeedsDisplay]; [labelLayer setValue:label forKey:@"text"]; [trayLayer addSublayer:labelLayer]; return trayLayer; } 48

12.MainView.m 파일에 initWithCoder: 메서드 재정의 -(id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if(self) mainLayer = [CALayer layer]; mainLayer.frame = self.bounds; mainLayer.contents = (id)([UIImage imageNamed:@"Background.png"].CGImage); [self.layer addSublayer:mainLayer]; trayLabelDelegate = [[TrayLabelDelegate alloc] init]; inTrayLayer = [self createTrayWithLabel:@"IN"]; inTrayLayer.position = CGPointMake(80, 60); outTrayLayer = [self createTrayWithLabel:@"OUT"]; outTrayLayer.position = CGPointMake(240, 60); photoRootLayer = [CALayer layer]; photoRootLayer.frame = self.bounds; [self.layer addSublayer:photoRootLayer]; int paperCount = 10; while (paperCount--) CALayer *sheetLayer = [CALayer layer]; sheetLayer.backgroundColor = [[UIColor whiteColor] CGColor]; sheetLayer.bounds = CGRectMake(0, 0, 60, 80); sheetLayer.position = inTrayLayer.position; sheetLayer.contents = (id)[[UIImage imageNamed:@"Photo.jpg"] CGImage]; [sheetLayer setValue:@"sheet" forKey:@"kind"]; [photoRootLayer addSublayer:sheetLayer]; } return self; 49

13.MainView.m 파일에 사용자 정의 메서드 생성 - (void)endDragAtPosition:(CGPoint)where { dragLayer.position = where; dragLayer.zPosition = 0; [dragLayer setValue:[NSNumber numberWithFloat:1.0f] forKeyPath:@"transform.scale"]; dragLayer = nil; } 14.MainView.m 파일에 dealloc 메서드 재정의 - (void)dealloc [trayLabelDelegate release]; [super dealloc]; 50

15.MainView.m 파일에 터치 메서드 재정의 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint viewPoint = [touch locationInView:self]; CGPoint where = [photoRootLayer convertPoint:viewPoint fromLayer:self.layer]; CALayer *hitLayer = [photoRootLayer hitTest:where]; if (hitLayer != nil && hitLayer != photoRootLayer) dragLayer = hitLayer; dragOrigin = hitLayer.position; dragLayer.zPosition = 2; [dragLayer setValue:[NSNumber numberWithFloat:1.5f] forKeyPath:@"transform.scale"]; [dragLayer setValue:[NSNumber numberWithFloat:0.0f] forKeyPath:@"transform.rotation.z"]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event if (dragLayer != nil) [CATransaction flush]; [CATransaction begin]; [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions]; dragLayer.position = where; [CATransaction commit]; 51

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { if(dragLayer != nil) UITouch *touch = [touches anyObject]; CGPoint viewPoint = [touch locationInView:self]; CGPoint where = [photoRootLayer convertPoint:viewPoint fromLayer:self.layer]; CALayer *dropLayer = [mainLayer hitTest:where]; if (dropLayer != nil && dropLayer != mainLayer) [self endDragAtPosition:dropLayer.position]; } else CGFloat r = (1000 - (random() % 2000)) / 1000.0f; CGFloat angle = r * M_PI_2; [dragLayer setValue:[NSNumber numberWithFloat:angle] forKeyPath:@"transform.rotation.z"]; [self endDragAtPosition:where]; - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event if (dragLayer != nil) [self endDragAtPosition:dragOrigin]; 52

CAGradientLayer 여러 가지 배경 색상이 적용된 레이어 멤버 @property(copy) NSArray *colors @property(copy) NSArray *locations @property CGPoint startPoint @property CGPoint endPoint 53

CAGradientLayer 54

1.Single View Application 프로젝트 생성(GradientLayerUse) 2.프로젝트에 QuartzCore 프레임워크 추가 3.UIView로 부터 상속받는 GradientView 생성 4.GradientView.m 파일에 헤더파일 import #import <QuartzCore/QuartzCore.h> 5.GradientView.m 파일에서 initWithFrame: 메서드 수정 - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) static NSMutableArray *colors = nil; if (colors == nil) colors = [[NSMutableArray alloc] initWithCapacity:3]; UIColor *color = nil; color = [UIColor colorWithRed:1 green:0 blue:0 alpha:1.0]; [colors addObject:(id)[color CGColor]]; color = [UIColor colorWithRed:0 green:1 blue:0 alpha:1.0]; color = [UIColor colorWithRed:0 green:0 blue:1 alpha:1.0]; [(CAGradientLayer *)self.layer setColors:colors]; [(CAGradientLayer *)self.layer setLocations:[NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0], [NSNumber numberWithFloat:0.67], [NSNumber numberWithFloat:1.0], nil]]; } return self; 55

6.GradientView.m 파일에 레이어를 변경하는 메서드 재정의 + (Class)layerClass { return [CAGradientLayer class]; } 7.ViewController.h 파일에 헤더파일을 추가하고 변수 선언 #import <UIKit/UIKit.h> #import "GradientView.h" @interface ViewController : UIViewController GradientView * gradientView; @end 8.ViewController.m 파일에 viewDidLoad 메서드 재정의 - (void)viewDidLoad [super viewDidLoad]; gradientView = [[GradientView alloc]initWithFrame:[[UIScreen mainScreen]bounds]]; [self.view addSubview:gradientView]; [gradientView release]; 56