SlideShare a Scribd company logo
1 of 57
Download to read offline
CS193P - Lecture 5
iPhone Application Development

Views
Drawing
Animation
Today’s Topics
• Questions from previous lectures or assignments?
• Views
• Drawing
• Animation
Views
View Fundamentals
• Rectangular area on screen
• Draws content
• Handles events
• Subclass of UIResponder (which defines event handling API)
• Views arranged in a hierarchical fashion
    every view has one superview
  ■

  ■ every view has zero or more subviews




• Questions that immediately arise:
    what view-related structures exist?
  ■

  ■ what is the coordinate system?
View-related Structures
• CGPoint
      location in space: x and y components
  ■


• CGSize
      dimensions of something: width and height components
  ■


• CGRect
      location and dimension: origin and size
  ■
Rects, Points and Sizes
                                                     y
          CGRect

                                    CGPoint
  origin                                                     80
                                          80
                                x                                  54
   size
                                          54
                            y
                                                    (0, 0)              x




                                                             144
                       CGSize

                            144
                   width
                                               72
                            72
                   height
View-related Structure

Creation Function           Example

                            CGPoint point = CGPointMake (100.0, 200.0);
CGPointMake (x, y)          point.x = 300.0;
                            point.y = 30.0;

                           CGSize size = CGSizeMake (42.0, 11.0);
CGSizeMake (width, height) size.width = 100.0;
                           size.height = 72.0;

                           CGRect rect = CGRectMake (100.0, 200.0,
CGRectMake (x, y,                                    42.0, 11.0);
            width, height) rect.origin.x = 0.0;
                           rect.size.width = 50.0;
UIView Coordinate System
  Origin in upper left corner
■

■ y axis grows downwards



                                0, 0
                                       +x




                                 +y
UIView Coordinate System
  Origin in upper left corner
■

■ y axis grows downwards



                                0, 0
                                                +x



                                       UIView


                                 +y
Location and Size
• View’s location and size expressed in two ways
    Frame is in terms of superview’s coordinate system
  ■

  ■ Bounds is in terms of local coordinate system
Location and Size
• View’s location and size expressed in two ways
    Frame is in terms of superview’s coordinate system
  ■

  ■ Bounds is in terms of local coordinate system




                                      View A
Location and Size
• View’s location and size expressed in two ways
         Frame is in terms of superview’s coordinate system
       ■

       ■ Bounds is in terms of local coordinate system

0, 0                       550
                                           View A




400
Location and Size
• View’s location and size expressed in two ways
         Frame is in terms of superview’s coordinate system
       ■

       ■ Bounds is in terms of local coordinate system

0, 0                       550
                                                    View A frame:
                                                       origin: 0, 0
                                           View A
                                                       size: 550 x 400

                                                    View A bounds:
                                                       origin: 0, 0
                                                       size: 550 x 400

400
Location and Size
• View’s location and size expressed in two ways
         Frame is in terms of superview’s coordinate system
       ■

       ■ Bounds is in terms of local coordinate system

0, 0                       550
                                                    View A frame:
                                                       origin: 0, 0
                                           View A
                                                       size: 550 x 400

                                                    View A bounds:
                                 View B                origin: 0, 0
                                                       size: 550 x 400

400
Location and Size
• View’s location and size expressed in two ways
         Frame is in terms of superview’s coordinate system
       ■

       ■ Bounds is in terms of local coordinate system

0, 0                       550
                                                    View A frame:
                                                       origin: 0, 0
                                           View A
                                                       size: 550 x 400
           200, 100
                                                    View A bounds:
                                 View B                origin: 0, 0
                                                       size: 550 x 400

400
Location and Size
• View’s location and size expressed in two ways
         Frame is in terms of superview’s coordinate system
       ■

       ■ Bounds is in terms of local coordinate system

0, 0                        550
                                                    View A frame:
                                                       origin: 0, 0
                                           View A
                                                       size: 550 x 400
           200, 100          200
                                                    View A bounds:
                                  View B               origin: 0, 0
                                                       size: 550 x 400

400                   250
Location and Size
• View’s location and size expressed in two ways
         Frame is in terms of superview’s coordinate system
       ■

       ■ Bounds is in terms of local coordinate system

0, 0                        550
                                                    View A frame:
                                                       origin: 0, 0
                                           View A
                                                       size: 550 x 400
           200, 100          200
                                                    View A bounds:
                                  View B               origin: 0, 0
                                                       size: 550 x 400

400                   250
                                                    View B frame:
                                                       origin: 200, 100
                                                       size: 200 x 250
Location and Size
• View’s location and size expressed in two ways
         Frame is in terms of superview’s coordinate system
       ■

       ■ Bounds is in terms of local coordinate system

0, 0                               550
                                                           View A frame:
                                                              origin: 0, 0
                                                  View A
                                                              size: 550 x 400
           200, 100                 200
                                                           View A bounds:
                            0, 0         View B               origin: 0, 0
                                                              size: 550 x 400

400                   250
                                                           View B frame:
                                                              origin: 200, 100
                                                              size: 200 x 250
Location and Size
• View’s location and size expressed in two ways
         Frame is in terms of superview’s coordinate system
       ■

       ■ Bounds is in terms of local coordinate system

0, 0                               550
                                                           View A frame:
                                                              origin: 0, 0
                                                  View A
                                                              size: 550 x 400
           200, 100                 200
                                                           View A bounds:
                            0, 0         View B               origin: 0, 0
                                                              size: 550 x 400

400                   250
                                                           View B frame:
                                                              origin: 200, 100
                                                              size: 200 x 250

                                                           View B bounds:
                                                              origin: 0, 0
                                                              size: 200 x 250
Frame and Bounds
• Which to use?
      Usually depends on the context
  ■


• If you are using a view, typically you use frame
• If you are implementing a view, typically you use bounds
• Matter of perspective
    From outside it’s usually the frame
  ■

  ■ From inside it’s usually the bounds




• Examples:
    Creating a view, positioning a view in superview - use frame
  ■

  ■ Handling events, drawing a view - use bounds
View Hierarchy - UIWindow
• Views live inside of a window
• Instance of UIWindow, container of all views for an iPhone app
    apps have single window
  ■

  ■ usually set up in template project


• UIWindow is actually just a view
      adds some additional functionality specific to top level view
  ■
View Hierarchy - Manipulation
• Add/remove views in IB or using UIView methods
 	 - (void)addSubview:(UIView *)view;
 	 - (void)removeFromSuperview;
• Manipulate the view hierarchy manually:
 	-   (void)insertSubview:(UIView *)view atIndex:(int)index;
 	-   (void)insertSubview:(UIView *)view belowSubview:(UIView *)view;
 	-   (void)insertSubview:(UIView *)view aboveSubview:(UIView *)view;
 	-   (void)exchangeSubviewAtIndex:(int)index
            withSubviewAtIndex:(int)otherIndex;
View Hierarchy - Ownership
• Superviews retain their subviews
• Not uncommon for views to only be retained by superview
    Be careful when removing!
  ■

  ■ Retain subview before removing if you want to reuse it


• Views can be temporarily hidden
      [theView setHidden:YES];
Creating Views
Where do views come from?
• Commonly Interface Builder
• Drag out any of the existing view objects (buttons, labels, etc)
• Or drag generic UIView and set custom class
Manual Creation
• Views are initialized using -initWithFrame:
 	 	 CGRect frame = CGRectMake(0, 0, 200, 150);
 	 	 UIView *myView = [[UIView alloc] initWithFrame:frame];

• Example:
 	 	 CGRect frame = CGRectMake(20, 45, 140, 21);
 	 	 UILabel *label = [[UILabel alloc] initWithFrame:frame];

 	 	 [window addSubview:label];
 	 	 [label setText:@”Number of sides:”];
 	 	 [label release]; // label now retained by window
Custom Views
• Subclass UIView
• For custom drawing, you override:
 	 	 	 	 - (void)drawRect:(CGRect)rect;
• For event handling, you override:
 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
Drawing Views
- (void)drawRect:(CGRect)rect
• UIView’s drawRect: implementation does nothing
      If no overridden drawRect: then backgroundColor used to fill
  ■


• Override - drawRect: to draw a custom view
      rect argument is area to draw
  ■


• When is it OK to call drawRect:?
Be Lazy
• drawRect: is invoked automatically
      Don’t call it directly!
  ■


• When a view needs to be redrawn, use:
 	 	 - (void)setNeedsDisplay;


• For example, in your controller:
 	 	 - (void)setNumberOfSides:(int)sides {
 	 	 	 	 	 	 numberOfSides = sides;
 	 	 	 	 	 	 [polygonView setNeedsDisplay];
 		}
CoreGraphics and Quartz 2D
• UIKit offers very basic drawing functionality
         UIRectFill(CGRect rect);
 	 	 	 	 UIRectFrame(CGRect rect);
• Many types and drawing functions defined in CoreGraphics
• CG is a C-based API, not Objective-C
• CG and Quartz 2D drawing engine define simple but powerful
 graphics primitives
    Graphics context
  ■

  ■ Transformations

  ■ Paths

  ■ Colors

  ■ Fonts

  ■ Painting operations
Graphics Contexts
• All drawing is done into an opaque graphics context
• Actual output destination could be a screen, bitmap buffer,
  printer, PDF document, etc.
• Graphics context setup automatically before invoking drawRect:
    Defines current path, line width, transform, etc.
  ■

  ■ Access the graphics context within drawRect: by calling

      	 	 (CGContextRef)UIGraphicsGetCurrentContext(void);
      Use CG calls to change settings
  ■


• Context only valid for current call to drawRect:
      Don’t try to cache them!
  ■
CG Wrappers
• Some CG functionality wrapped by UIKit
• UIColor
    Convenience for getting common colors
  ■

  ■ Easily set the fill and/or stroke colors when drawing


            UIColor *redColor = [UIColor redColor];
      	 	 	 [redColor set];
      	 	 	 // drawing will be done in red
• UIFont
    Access system font
  ■

  ■ Get font by name


      	 	 	 UIFont *font = [UIFont systemFontOfSize:14.0];
      	 	 	 [myLabel setFont:font];
Simple drawRect: example
• Draw a solid color and shape
- (void)drawRect:(CGRect)rect {
   CGRect bounds = [self bounds];

    [[UIColor grayColor] set];
    UIRectFill (bounds);

    CGRect square = CGRectMake (10, 10, 50, 100);
    [[UIColor redColor] set];
    UIRectFill (square);

    [[UIColor blackColor] set];
    UIRectFrame (square);
}
Simple drawRect: example
• Draw a solid color and shape
- (void)drawRect:(CGRect)rect {
   CGRect bounds = [self bounds];

    [[UIColor grayColor] set];
    UIRectFill (bounds);

    CGRect square = CGRectMake (10, 10, 50, 100);
    [[UIColor redColor] set];
    UIRectFill (square);

    [[UIColor blackColor] set];
    UIRectFrame (square);
}
Drawing More Complex Shapes
• Common steps for drawRect: are
    Get current graphics context
  ■

  ■ Define a path

  ■ Set a color

  ■ Stroke or fill path

  ■ Repeat, if necessary
Paths
• CoreGraphics paths define shapes
• Made up of lines, arcs, curves and rectangles
• Creation and drawing of paths are two distinct operations
      Define path first, then draw it
  ■
CGPath
• Two parallel sets of functions for using paths
    CGContext “convenience” throwaway functions
  ■

  ■ CGPath functions for creating reusable paths




           CGContext                       CGPath
 CGContextMoveToPoint           CGPathMoveToPoint
 CGContextLineToPoint           CGPathAddLineToPoint
 CGContextAddArcToPoint         CGPathAddArcToPoint
 CGContextClosePath             CGPathCloseSubPath
  And so on and so on . . .
Simple Path Example
- (void)drawRect:(CGRect)rect {
   CGContextRef context = UIGraphicsGetCurrentContext();

    [[UIColor grayColor] set];
    UIRectFill ([self bounds]);

    CGContextBeginPath (context);
    CGContextMoveToPoint (context, 75, 10);
    CGContextAddLineToPoint (context, 10, 150);
    CGContextAddLineToPoint (context, 160, 150);
    CGContextClosePath (context);

    [[UIColor redColor] setFill];
    [[UIColor blackColor] setStroke];
    CGContextDrawPath (context, kCGPathFillStroke);
}
Simple Path Example
- (void)drawRect:(CGRect)rect {
   CGContextRef context = UIGraphicsGetCurrentContext();

    [[UIColor grayColor] set];
    UIRectFill ([self bounds]);

    CGContextBeginPath (context);
    CGContextMoveToPoint (context, 75, 10);
    CGContextAddLineToPoint (context, 10, 150);
    CGContextAddLineToPoint (context, 160, 150);
    CGContextClosePath (context);

    [[UIColor redColor] setFill];
    [[UIColor blackColor] setStroke];
    CGContextDrawPath (context, kCGPathFillStroke);
}
More Drawing Information
• UIView Class Reference
• CGContext Reference
• “Quartz 2D Programming Guide”
• Lots of samples in the iPhone Dev Center
View Properties & Animation
View Properties
• Views have many properties
      bounds, alpha, transform, backgroundColor, hidden, etc
  ■


• View subclasses add many more
    UIControl: enabled, selected, highlighted
  ■

  ■ UILabel: font, textColor, shadowColor, textAlignment, etc

  ■ UIButton: font, title, titleColor, image, backgroundImage


• Most properties settable in IB
      If not in Attributes Inspector, need to set in code
  ■


• See class reference documentation for all properties
Animating Views
• Consider example where a view needs to resize or change
  layout dynamically
• For example, user toggles a switch which displays additional
  views
Animating Views
• Consider example where a view needs to resize or change
  layout dynamically
• For example, user toggles a switch which displays additional
  views
Animating Views
• Consider example where a view needs to resize or change
  layout dynamically
• For example, user toggles a switch which displays additional
  views
UIView Animations
• UIView supports a number of animatable properties
      frame, bounds, center, alpha, transform
  ■


• Create “blocks” around changes to animatable properties
• Animations run asynchronously and automatically
Other Animation Options
• Additional methods for other options
    delay before starting animation
  ■

  ■ start animation at specific time

  ■ set animation curve (ease in/out, ease in, ease out, linear)

  ■ repeat count

  ■ autoreverses (e.g. ping pong back and forth)
Animation Examples
View Animation Example
- (void)showAdvancedOptions {
    // assume polygonView and optionsView
    [UIView beginAnimations:@”advancedAnimations” context:nil];
    [UIView setAnimationDuration:0.3];


    // make optionsView visible (alpha is currently 0.0)
    optionsView.alpha = 1.0;

    // move the polygonView down
    CGRect polygonFrame = polygonView.frame;
    polygonFrame.origin.y += 200;
    polygonView.frame = polygonFrame;


    [UIView commitAnimations];

}
Knowing When Animations Finish
• UIView animations allow for a delegate
 	 	 	 [UIView setAnimationDelegate:myController];


• myController will have callbacks invoked before and after
     - (void)animationWillStart:(NSString *)animationID
             context:(void *)context;

     - (void)animationDidStop:(NSString *)animationID
             finished:(NSNumber *)finished
             context:(void *)context;

• Can provide custom selectors if desired, for example
     [UIView setAnimationWillStartSelector:
                    @selector(animationWillStart)];
     [UIView setAnimationDidStopSelector:
                    @selector(animationDidStop)];
How Does It Work?
• Is drawRect: invoked repeatedly?
• Do I have to run some kind of timer in order to drive the
  animation?
• Is it magic?
Core Animation
• Hardware accelerated rendering engine
• UIViews are backed by Core Animation “layers”
• First time drawRect: is called on UIView results are cached
    If view’s contents don’t change drawRect: never called again
  ■

  ■ Cached results used to render view

  ■ Layers maintained in separate hierarchy managed by separate

    process
• Rendering of layers uses cached results
• Property animations done automatically by manipulating layers
View Transforms
• Every view has a transform property
      used to apply scaling, rotation and translation to a view
  ■


• By default a view’s transform is the identity transform
      no affect on the view
  ■


• CGAffineTransform structure used to represent transform
• Use CG functions to create, modify transforms
      CGAffineTransform Functions (just a small example set)
  CGAffineTransformScale (transform, xScale, yScale)
  CGAffineTransformRotate (transform, angle)

  CGAffineTransformTranslate (transform, xDelta, yDelta)
More Animation Information
• iPhone OS Programming Guide
      “Modifying Views at Runtime” section
  ■


• Core Animation Programming Guide
View Example Project
Questions?

More Related Content

What's hot

Dronekitによる python apiとアプリ開発の概要
Dronekitによる python apiとアプリ開発の概要Dronekitによる python apiとアプリ開発の概要
Dronekitによる python apiとアプリ開発の概要Masami Ogoshi
 
会議を組み立てるABC
会議を組み立てるABC会議を組み立てるABC
会議を組み立てるABCShogoTokuda
 
Implementing CATiledLayer
Implementing CATiledLayerImplementing CATiledLayer
Implementing CATiledLayerJesse Collis
 
Modular Navigation with React Navigation
Modular Navigation with React NavigationModular Navigation with React Navigation
Modular Navigation with React NavigationWilliam Santos
 
이원, 절차적 지형 생성과 하이트필드의 사원, NDC2011
이원, 절차적 지형 생성과 하이트필드의 사원, NDC2011이원, 절차적 지형 생성과 하이트필드의 사원, NDC2011
이원, 절차적 지형 생성과 하이트필드의 사원, NDC2011devCAT Studio, NEXON
 
4. 캐릭터 애니메이션
4. 캐릭터 애니메이션4. 캐릭터 애니메이션
4. 캐릭터 애니메이션MinGeun Park
 
Criando microsserviços em PHP
Criando microsserviços em PHPCriando microsserviços em PHP
Criando microsserviços em PHPFlávio Lisboa
 
[IMQA] 빠른 웹페이지 만들기 - 당신의 웹페이지는 몇 점인가요?
[IMQA] 빠른 웹페이지 만들기 - 당신의 웹페이지는 몇 점인가요?[IMQA] 빠른 웹페이지 만들기 - 당신의 웹페이지는 몇 점인가요?
[IMQA] 빠른 웹페이지 만들기 - 당신의 웹페이지는 몇 점인가요?IMQA
 
Crestron AirMedia vs Barco ClickShare Review
Crestron AirMedia vs Barco ClickShare ReviewCrestron AirMedia vs Barco ClickShare Review
Crestron AirMedia vs Barco ClickShare ReviewPaul Richards
 
지급결제/송금 프로세스 및 시스템 구성 - PART II (ver 4.0)
지급결제/송금 프로세스 및 시스템 구성 - PART II (ver 4.0)지급결제/송금 프로세스 및 시스템 구성 - PART II (ver 4.0)
지급결제/송금 프로세스 및 시스템 구성 - PART II (ver 4.0)Juhyeon Lee
 
[SOSCON 2017] 주니어 개발자 5000명, 개발 해서 남 주자
[SOSCON 2017] 주니어 개발자 5000명, 개발 해서 남 주자[SOSCON 2017] 주니어 개발자 5000명, 개발 해서 남 주자
[SOSCON 2017] 주니어 개발자 5000명, 개발 해서 남 주자Yurim Jin
 
Building AR and VR Experiences
Building AR and VR ExperiencesBuilding AR and VR Experiences
Building AR and VR ExperiencesMark Billinghurst
 
Virtualization concept slideshare
Virtualization concept slideshareVirtualization concept slideshare
Virtualization concept slideshareYogesh Kumar
 
What is Virtualization
What is VirtualizationWhat is Virtualization
What is VirtualizationIsrael Marcus
 
코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011Esun Kim
 
Lecture7 Example VR Applications
Lecture7 Example VR ApplicationsLecture7 Example VR Applications
Lecture7 Example VR ApplicationsMark Billinghurst
 

What's hot (20)

Dronekitによる python apiとアプリ開発の概要
Dronekitによる python apiとアプリ開発の概要Dronekitによる python apiとアプリ開発の概要
Dronekitによる python apiとアプリ開発の概要
 
会議を組み立てるABC
会議を組み立てるABC会議を組み立てるABC
会議を組み立てるABC
 
Implementing CATiledLayer
Implementing CATiledLayerImplementing CATiledLayer
Implementing CATiledLayer
 
Modular Navigation with React Navigation
Modular Navigation with React NavigationModular Navigation with React Navigation
Modular Navigation with React Navigation
 
이원, 절차적 지형 생성과 하이트필드의 사원, NDC2011
이원, 절차적 지형 생성과 하이트필드의 사원, NDC2011이원, 절차적 지형 생성과 하이트필드의 사원, NDC2011
이원, 절차적 지형 생성과 하이트필드의 사원, NDC2011
 
4. 캐릭터 애니메이션
4. 캐릭터 애니메이션4. 캐릭터 애니메이션
4. 캐릭터 애니메이션
 
Virtualization basics
Virtualization basics Virtualization basics
Virtualization basics
 
Hypervisors
HypervisorsHypervisors
Hypervisors
 
Criando microsserviços em PHP
Criando microsserviços em PHPCriando microsserviços em PHP
Criando microsserviços em PHP
 
[IMQA] 빠른 웹페이지 만들기 - 당신의 웹페이지는 몇 점인가요?
[IMQA] 빠른 웹페이지 만들기 - 당신의 웹페이지는 몇 점인가요?[IMQA] 빠른 웹페이지 만들기 - 당신의 웹페이지는 몇 점인가요?
[IMQA] 빠른 웹페이지 만들기 - 당신의 웹페이지는 몇 점인가요?
 
Produktkatalog von Hirnböck Stabau
Produktkatalog von Hirnböck StabauProduktkatalog von Hirnböck Stabau
Produktkatalog von Hirnböck Stabau
 
Virtualization
VirtualizationVirtualization
Virtualization
 
Crestron AirMedia vs Barco ClickShare Review
Crestron AirMedia vs Barco ClickShare ReviewCrestron AirMedia vs Barco ClickShare Review
Crestron AirMedia vs Barco ClickShare Review
 
지급결제/송금 프로세스 및 시스템 구성 - PART II (ver 4.0)
지급결제/송금 프로세스 및 시스템 구성 - PART II (ver 4.0)지급결제/송금 프로세스 및 시스템 구성 - PART II (ver 4.0)
지급결제/송금 프로세스 및 시스템 구성 - PART II (ver 4.0)
 
[SOSCON 2017] 주니어 개발자 5000명, 개발 해서 남 주자
[SOSCON 2017] 주니어 개발자 5000명, 개발 해서 남 주자[SOSCON 2017] 주니어 개발자 5000명, 개발 해서 남 주자
[SOSCON 2017] 주니어 개발자 5000명, 개발 해서 남 주자
 
Building AR and VR Experiences
Building AR and VR ExperiencesBuilding AR and VR Experiences
Building AR and VR Experiences
 
Virtualization concept slideshare
Virtualization concept slideshareVirtualization concept slideshare
Virtualization concept slideshare
 
What is Virtualization
What is VirtualizationWhat is Virtualization
What is Virtualization
 
코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011
 
Lecture7 Example VR Applications
Lecture7 Example VR ApplicationsLecture7 Example VR Applications
Lecture7 Example VR Applications
 

Viewers also liked

Интуит. Разработка приложений для iOS. Лекция 9. Нестандартный интерфейс
Интуит. Разработка приложений для iOS. Лекция 9. Нестандартный интерфейсИнтуит. Разработка приложений для iOS. Лекция 9. Нестандартный интерфейс
Интуит. Разработка приложений для iOS. Лекция 9. Нестандартный интерфейсГлеб Тарасов
 
06 View Controllers
06 View Controllers06 View Controllers
06 View ControllersMahmoud
 
02 Objective C
02 Objective C02 Objective C
02 Objective CMahmoud
 
03 Custom Classes
03 Custom Classes03 Custom Classes
03 Custom ClassesMahmoud
 
01 Introduction
01 Introduction01 Introduction
01 IntroductionMahmoud
 
04 Model View Controller
04 Model View Controller04 Model View Controller
04 Model View ControllerMahmoud
 
Роман Бусыгин "Yandex Map Kit для iOS в примерах"
Роман Бусыгин "Yandex Map Kit для iOS в примерах"Роман Бусыгин "Yandex Map Kit для iOS в примерах"
Роман Бусыгин "Yandex Map Kit для iOS в примерах"Yandex
 
Интуит. Разработка приложений для iOS. Лекция 11. Расширенные возможности уст...
Интуит. Разработка приложений для iOS. Лекция 11. Расширенные возможности уст...Интуит. Разработка приложений для iOS. Лекция 11. Расширенные возможности уст...
Интуит. Разработка приложений для iOS. Лекция 11. Расширенные возможности уст...Глеб Тарасов
 
Архитектура компилятора Swift
Архитектура компилятора SwiftАрхитектура компилятора Swift
Архитектура компилятора SwiftAndrey Volobuev
 
Преимущества и недостатки языка Swift
Преимущества и недостатки языка SwiftПреимущества и недостатки языка Swift
Преимущества и недостатки языка SwiftAndrey Volobuev
 
Objective C Tricks
Objective C TricksObjective C Tricks
Objective C TricksInova LLC
 
Rambler.iOS #6: App delegate - разделяй и властвуй
Rambler.iOS #6: App delegate - разделяй и властвуйRambler.iOS #6: App delegate - разделяй и властвуй
Rambler.iOS #6: App delegate - разделяй и властвуйRAMBLER&Co
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Мобильный веб: назад в будущее
Мобильный веб: назад в будущееМобильный веб: назад в будущее
Мобильный веб: назад в будущееBadoo Development
 
Технологии vs коммуникации: что важнее?
Технологии vs коммуникации: что важнее?Технологии vs коммуникации: что важнее?
Технологии vs коммуникации: что важнее?Badoo Development
 
Багфиксинг процесса разработки в iOS: взгляд с двух сторон
Багфиксинг процесса разработки в iOS: взгляд с двух сторонБагфиксинг процесса разработки в iOS: взгляд с двух сторон
Багфиксинг процесса разработки в iOS: взгляд с двух сторонBadoo Development
 

Viewers also liked (20)

Интуит. Разработка приложений для iOS. Лекция 9. Нестандартный интерфейс
Интуит. Разработка приложений для iOS. Лекция 9. Нестандартный интерфейсИнтуит. Разработка приложений для iOS. Лекция 9. Нестандартный интерфейс
Интуит. Разработка приложений для iOS. Лекция 9. Нестандартный интерфейс
 
Animation in iOS
Animation in iOSAnimation in iOS
Animation in iOS
 
005
005005
005
 
06 View Controllers
06 View Controllers06 View Controllers
06 View Controllers
 
09 Data
09 Data09 Data
09 Data
 
02 Objective C
02 Objective C02 Objective C
02 Objective C
 
iOS: View Controllers
iOS: View ControllersiOS: View Controllers
iOS: View Controllers
 
03 Custom Classes
03 Custom Classes03 Custom Classes
03 Custom Classes
 
01 Introduction
01 Introduction01 Introduction
01 Introduction
 
04 Model View Controller
04 Model View Controller04 Model View Controller
04 Model View Controller
 
Роман Бусыгин "Yandex Map Kit для iOS в примерах"
Роман Бусыгин "Yandex Map Kit для iOS в примерах"Роман Бусыгин "Yandex Map Kit для iOS в примерах"
Роман Бусыгин "Yandex Map Kit для iOS в примерах"
 
Интуит. Разработка приложений для iOS. Лекция 11. Расширенные возможности уст...
Интуит. Разработка приложений для iOS. Лекция 11. Расширенные возможности уст...Интуит. Разработка приложений для iOS. Лекция 11. Расширенные возможности уст...
Интуит. Разработка приложений для iOS. Лекция 11. Расширенные возможности уст...
 
Архитектура компилятора Swift
Архитектура компилятора SwiftАрхитектура компилятора Swift
Архитектура компилятора Swift
 
Преимущества и недостатки языка Swift
Преимущества и недостатки языка SwiftПреимущества и недостатки языка Swift
Преимущества и недостатки языка Swift
 
Objective C Tricks
Objective C TricksObjective C Tricks
Objective C Tricks
 
Rambler.iOS #6: App delegate - разделяй и властвуй
Rambler.iOS #6: App delegate - разделяй и властвуйRambler.iOS #6: App delegate - разделяй и властвуй
Rambler.iOS #6: App delegate - разделяй и властвуй
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Мобильный веб: назад в будущее
Мобильный веб: назад в будущееМобильный веб: назад в будущее
Мобильный веб: назад в будущее
 
Технологии vs коммуникации: что важнее?
Технологии vs коммуникации: что важнее?Технологии vs коммуникации: что важнее?
Технологии vs коммуникации: что важнее?
 
Багфиксинг процесса разработки в iOS: взгляд с двух сторон
Багфиксинг процесса разработки в iOS: взгляд с двух сторонБагфиксинг процесса разработки в iOS: взгляд с двух сторон
Багфиксинг процесса разработки в iOS: взгляд с двух сторон
 

Recently uploaded

What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?TechSoup
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxDr. Santhosh Kumar. N
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphNetziValdelomar1
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.EnglishCEIPdeSigeiro
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxheathfieldcps1
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesCeline George
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxDr. Asif Anas
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfMohonDas
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxAditiChauhan701637
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfYu Kanazawa / Osaka University
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapitolTechU
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesMohammad Hassany
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfTechSoup
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxraviapr7
 
Quality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICEQuality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICESayali Powar
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...Nguyen Thanh Tu Collection
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxSaurabhParmar42
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17Celine George
 

Recently uploaded (20)

What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptx
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a Paragraph
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024
 
Prelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quizPrelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quiz
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 Sales
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptx
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdf
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptx
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptx
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming Classes
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptx
 
Quality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICEQuality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICE
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptx
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17
 

CS193P Lecture 5 View Animation

  • 1. CS193P - Lecture 5 iPhone Application Development Views Drawing Animation
  • 2. Today’s Topics • Questions from previous lectures or assignments? • Views • Drawing • Animation
  • 4. View Fundamentals • Rectangular area on screen • Draws content • Handles events • Subclass of UIResponder (which defines event handling API) • Views arranged in a hierarchical fashion every view has one superview ■ ■ every view has zero or more subviews • Questions that immediately arise: what view-related structures exist? ■ ■ what is the coordinate system?
  • 5. View-related Structures • CGPoint location in space: x and y components ■ • CGSize dimensions of something: width and height components ■ • CGRect location and dimension: origin and size ■
  • 6. Rects, Points and Sizes y CGRect CGPoint origin 80 80 x 54 size 54 y (0, 0) x 144 CGSize 144 width 72 72 height
  • 7. View-related Structure Creation Function Example CGPoint point = CGPointMake (100.0, 200.0); CGPointMake (x, y) point.x = 300.0; point.y = 30.0; CGSize size = CGSizeMake (42.0, 11.0); CGSizeMake (width, height) size.width = 100.0; size.height = 72.0; CGRect rect = CGRectMake (100.0, 200.0, CGRectMake (x, y, 42.0, 11.0); width, height) rect.origin.x = 0.0; rect.size.width = 50.0;
  • 8. UIView Coordinate System Origin in upper left corner ■ ■ y axis grows downwards 0, 0 +x +y
  • 9. UIView Coordinate System Origin in upper left corner ■ ■ y axis grows downwards 0, 0 +x UIView +y
  • 10. Location and Size • View’s location and size expressed in two ways Frame is in terms of superview’s coordinate system ■ ■ Bounds is in terms of local coordinate system
  • 11. Location and Size • View’s location and size expressed in two ways Frame is in terms of superview’s coordinate system ■ ■ Bounds is in terms of local coordinate system View A
  • 12. Location and Size • View’s location and size expressed in two ways Frame is in terms of superview’s coordinate system ■ ■ Bounds is in terms of local coordinate system 0, 0 550 View A 400
  • 13. Location and Size • View’s location and size expressed in two ways Frame is in terms of superview’s coordinate system ■ ■ Bounds is in terms of local coordinate system 0, 0 550 View A frame: origin: 0, 0 View A size: 550 x 400 View A bounds: origin: 0, 0 size: 550 x 400 400
  • 14. Location and Size • View’s location and size expressed in two ways Frame is in terms of superview’s coordinate system ■ ■ Bounds is in terms of local coordinate system 0, 0 550 View A frame: origin: 0, 0 View A size: 550 x 400 View A bounds: View B origin: 0, 0 size: 550 x 400 400
  • 15. Location and Size • View’s location and size expressed in two ways Frame is in terms of superview’s coordinate system ■ ■ Bounds is in terms of local coordinate system 0, 0 550 View A frame: origin: 0, 0 View A size: 550 x 400 200, 100 View A bounds: View B origin: 0, 0 size: 550 x 400 400
  • 16. Location and Size • View’s location and size expressed in two ways Frame is in terms of superview’s coordinate system ■ ■ Bounds is in terms of local coordinate system 0, 0 550 View A frame: origin: 0, 0 View A size: 550 x 400 200, 100 200 View A bounds: View B origin: 0, 0 size: 550 x 400 400 250
  • 17. Location and Size • View’s location and size expressed in two ways Frame is in terms of superview’s coordinate system ■ ■ Bounds is in terms of local coordinate system 0, 0 550 View A frame: origin: 0, 0 View A size: 550 x 400 200, 100 200 View A bounds: View B origin: 0, 0 size: 550 x 400 400 250 View B frame: origin: 200, 100 size: 200 x 250
  • 18. Location and Size • View’s location and size expressed in two ways Frame is in terms of superview’s coordinate system ■ ■ Bounds is in terms of local coordinate system 0, 0 550 View A frame: origin: 0, 0 View A size: 550 x 400 200, 100 200 View A bounds: 0, 0 View B origin: 0, 0 size: 550 x 400 400 250 View B frame: origin: 200, 100 size: 200 x 250
  • 19. Location and Size • View’s location and size expressed in two ways Frame is in terms of superview’s coordinate system ■ ■ Bounds is in terms of local coordinate system 0, 0 550 View A frame: origin: 0, 0 View A size: 550 x 400 200, 100 200 View A bounds: 0, 0 View B origin: 0, 0 size: 550 x 400 400 250 View B frame: origin: 200, 100 size: 200 x 250 View B bounds: origin: 0, 0 size: 200 x 250
  • 20. Frame and Bounds • Which to use? Usually depends on the context ■ • If you are using a view, typically you use frame • If you are implementing a view, typically you use bounds • Matter of perspective From outside it’s usually the frame ■ ■ From inside it’s usually the bounds • Examples: Creating a view, positioning a view in superview - use frame ■ ■ Handling events, drawing a view - use bounds
  • 21. View Hierarchy - UIWindow • Views live inside of a window • Instance of UIWindow, container of all views for an iPhone app apps have single window ■ ■ usually set up in template project • UIWindow is actually just a view adds some additional functionality specific to top level view ■
  • 22. View Hierarchy - Manipulation • Add/remove views in IB or using UIView methods - (void)addSubview:(UIView *)view; - (void)removeFromSuperview; • Manipulate the view hierarchy manually: - (void)insertSubview:(UIView *)view atIndex:(int)index; - (void)insertSubview:(UIView *)view belowSubview:(UIView *)view; - (void)insertSubview:(UIView *)view aboveSubview:(UIView *)view; - (void)exchangeSubviewAtIndex:(int)index withSubviewAtIndex:(int)otherIndex;
  • 23. View Hierarchy - Ownership • Superviews retain their subviews • Not uncommon for views to only be retained by superview Be careful when removing! ■ ■ Retain subview before removing if you want to reuse it • Views can be temporarily hidden [theView setHidden:YES];
  • 25. Where do views come from? • Commonly Interface Builder • Drag out any of the existing view objects (buttons, labels, etc) • Or drag generic UIView and set custom class
  • 26. Manual Creation • Views are initialized using -initWithFrame: CGRect frame = CGRectMake(0, 0, 200, 150); UIView *myView = [[UIView alloc] initWithFrame:frame]; • Example: CGRect frame = CGRectMake(20, 45, 140, 21); UILabel *label = [[UILabel alloc] initWithFrame:frame]; [window addSubview:label]; [label setText:@”Number of sides:”]; [label release]; // label now retained by window
  • 27. Custom Views • Subclass UIView • For custom drawing, you override: - (void)drawRect:(CGRect)rect; • For event handling, you override: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
  • 29. - (void)drawRect:(CGRect)rect • UIView’s drawRect: implementation does nothing If no overridden drawRect: then backgroundColor used to fill ■ • Override - drawRect: to draw a custom view rect argument is area to draw ■ • When is it OK to call drawRect:?
  • 30. Be Lazy • drawRect: is invoked automatically Don’t call it directly! ■ • When a view needs to be redrawn, use: - (void)setNeedsDisplay; • For example, in your controller: - (void)setNumberOfSides:(int)sides { numberOfSides = sides; [polygonView setNeedsDisplay]; }
  • 31. CoreGraphics and Quartz 2D • UIKit offers very basic drawing functionality UIRectFill(CGRect rect); UIRectFrame(CGRect rect); • Many types and drawing functions defined in CoreGraphics • CG is a C-based API, not Objective-C • CG and Quartz 2D drawing engine define simple but powerful graphics primitives Graphics context ■ ■ Transformations ■ Paths ■ Colors ■ Fonts ■ Painting operations
  • 32. Graphics Contexts • All drawing is done into an opaque graphics context • Actual output destination could be a screen, bitmap buffer, printer, PDF document, etc. • Graphics context setup automatically before invoking drawRect: Defines current path, line width, transform, etc. ■ ■ Access the graphics context within drawRect: by calling (CGContextRef)UIGraphicsGetCurrentContext(void); Use CG calls to change settings ■ • Context only valid for current call to drawRect: Don’t try to cache them! ■
  • 33. CG Wrappers • Some CG functionality wrapped by UIKit • UIColor Convenience for getting common colors ■ ■ Easily set the fill and/or stroke colors when drawing UIColor *redColor = [UIColor redColor]; [redColor set]; // drawing will be done in red • UIFont Access system font ■ ■ Get font by name UIFont *font = [UIFont systemFontOfSize:14.0]; [myLabel setFont:font];
  • 34. Simple drawRect: example • Draw a solid color and shape - (void)drawRect:(CGRect)rect { CGRect bounds = [self bounds]; [[UIColor grayColor] set]; UIRectFill (bounds); CGRect square = CGRectMake (10, 10, 50, 100); [[UIColor redColor] set]; UIRectFill (square); [[UIColor blackColor] set]; UIRectFrame (square); }
  • 35. Simple drawRect: example • Draw a solid color and shape - (void)drawRect:(CGRect)rect { CGRect bounds = [self bounds]; [[UIColor grayColor] set]; UIRectFill (bounds); CGRect square = CGRectMake (10, 10, 50, 100); [[UIColor redColor] set]; UIRectFill (square); [[UIColor blackColor] set]; UIRectFrame (square); }
  • 36. Drawing More Complex Shapes • Common steps for drawRect: are Get current graphics context ■ ■ Define a path ■ Set a color ■ Stroke or fill path ■ Repeat, if necessary
  • 37. Paths • CoreGraphics paths define shapes • Made up of lines, arcs, curves and rectangles • Creation and drawing of paths are two distinct operations Define path first, then draw it ■
  • 38. CGPath • Two parallel sets of functions for using paths CGContext “convenience” throwaway functions ■ ■ CGPath functions for creating reusable paths CGContext CGPath CGContextMoveToPoint CGPathMoveToPoint CGContextLineToPoint CGPathAddLineToPoint CGContextAddArcToPoint CGPathAddArcToPoint CGContextClosePath CGPathCloseSubPath And so on and so on . . .
  • 39. Simple Path Example - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); [[UIColor grayColor] set]; UIRectFill ([self bounds]); CGContextBeginPath (context); CGContextMoveToPoint (context, 75, 10); CGContextAddLineToPoint (context, 10, 150); CGContextAddLineToPoint (context, 160, 150); CGContextClosePath (context); [[UIColor redColor] setFill]; [[UIColor blackColor] setStroke]; CGContextDrawPath (context, kCGPathFillStroke); }
  • 40. Simple Path Example - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); [[UIColor grayColor] set]; UIRectFill ([self bounds]); CGContextBeginPath (context); CGContextMoveToPoint (context, 75, 10); CGContextAddLineToPoint (context, 10, 150); CGContextAddLineToPoint (context, 160, 150); CGContextClosePath (context); [[UIColor redColor] setFill]; [[UIColor blackColor] setStroke]; CGContextDrawPath (context, kCGPathFillStroke); }
  • 41. More Drawing Information • UIView Class Reference • CGContext Reference • “Quartz 2D Programming Guide” • Lots of samples in the iPhone Dev Center
  • 42. View Properties & Animation
  • 43. View Properties • Views have many properties bounds, alpha, transform, backgroundColor, hidden, etc ■ • View subclasses add many more UIControl: enabled, selected, highlighted ■ ■ UILabel: font, textColor, shadowColor, textAlignment, etc ■ UIButton: font, title, titleColor, image, backgroundImage • Most properties settable in IB If not in Attributes Inspector, need to set in code ■ • See class reference documentation for all properties
  • 44. Animating Views • Consider example where a view needs to resize or change layout dynamically • For example, user toggles a switch which displays additional views
  • 45. Animating Views • Consider example where a view needs to resize or change layout dynamically • For example, user toggles a switch which displays additional views
  • 46. Animating Views • Consider example where a view needs to resize or change layout dynamically • For example, user toggles a switch which displays additional views
  • 47. UIView Animations • UIView supports a number of animatable properties frame, bounds, center, alpha, transform ■ • Create “blocks” around changes to animatable properties • Animations run asynchronously and automatically
  • 48. Other Animation Options • Additional methods for other options delay before starting animation ■ ■ start animation at specific time ■ set animation curve (ease in/out, ease in, ease out, linear) ■ repeat count ■ autoreverses (e.g. ping pong back and forth)
  • 50. View Animation Example - (void)showAdvancedOptions { // assume polygonView and optionsView [UIView beginAnimations:@”advancedAnimations” context:nil]; [UIView setAnimationDuration:0.3]; // make optionsView visible (alpha is currently 0.0) optionsView.alpha = 1.0; // move the polygonView down CGRect polygonFrame = polygonView.frame; polygonFrame.origin.y += 200; polygonView.frame = polygonFrame; [UIView commitAnimations]; }
  • 51. Knowing When Animations Finish • UIView animations allow for a delegate [UIView setAnimationDelegate:myController]; • myController will have callbacks invoked before and after - (void)animationWillStart:(NSString *)animationID context:(void *)context; - (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context; • Can provide custom selectors if desired, for example [UIView setAnimationWillStartSelector: @selector(animationWillStart)]; [UIView setAnimationDidStopSelector: @selector(animationDidStop)];
  • 52. How Does It Work? • Is drawRect: invoked repeatedly? • Do I have to run some kind of timer in order to drive the animation? • Is it magic?
  • 53. Core Animation • Hardware accelerated rendering engine • UIViews are backed by Core Animation “layers” • First time drawRect: is called on UIView results are cached If view’s contents don’t change drawRect: never called again ■ ■ Cached results used to render view ■ Layers maintained in separate hierarchy managed by separate process • Rendering of layers uses cached results • Property animations done automatically by manipulating layers
  • 54. View Transforms • Every view has a transform property used to apply scaling, rotation and translation to a view ■ • By default a view’s transform is the identity transform no affect on the view ■ • CGAffineTransform structure used to represent transform • Use CG functions to create, modify transforms CGAffineTransform Functions (just a small example set) CGAffineTransformScale (transform, xScale, yScale) CGAffineTransformRotate (transform, angle) CGAffineTransformTranslate (transform, xDelta, yDelta)
  • 55. More Animation Information • iPhone OS Programming Guide “Modifying Views at Runtime” section ■ • Core Animation Programming Guide