SlideShare una empresa de Scribd logo
1 de 67
Descargar para leer sin conexión
Chapter 9
               Core Graphics
                  Bit Academy
Quartz

                        Your App

                Cocoa Touch(UIKit)
                        Core Animation
               Quartz
                        Core Graphics

                Graphics Hardware
Drawing Quartz and UIKIT

               •   Quartz is the general name for the native window server and
                   drawing technology in iOS.

               •   Core Graphics framework
                                                        .
                                                  .

                   •   Graphics contexts
                   •   Paths
                   •   Images and bitmaps
                   •   Transparency layers
                   •   Colors, pattern colors, and color spaces
                   •   Gradients and shadings
                   •   Fonts
                   •   PDF content
Page
               •   Quartz   painter model   .

               •                                page
                     .

               •   page                          .
Graphics Context
               •   Graphics Context


                   •
                   •                        (        ,     )

               •
                               User Space   Device Space

                                                 .
Graphics Context
Graphics Context




                            Your App

                        Cocoa Touch(UIKit)
                               Quartz
                            Core Animation
                            Core Graphics


                        Graphics Hardware
Graphics Context

                                      Graphics Context              .

               • A bitmap graphics context                              allows you to paint RGB colors,
                   CMYK colors, or grayscale into a bitmap. A bitmap is a rectangular array (or raster)
                   of pixels, each pixel representing a point in an image. Bitmap images are also called
                   sampled images. See “Creating a Bitmap Graphics Context.”
               • A PDF graphics context allows you to create a PDF file. In a
                   PDF file, your drawing is preserved as a sequence of commands. There are some
                   significant differences between PDF files and bitmaps:
                     1 PDF files, unlike bitmaps, may contain more than one page.
                     2 When you draw a page from a PDF file on a different device, the resulting
                         image is optimized for the display characteristics of that device.
                     3 PDF files are resolution independent by nature—the size at which they are
                         drawn can be increased or decreased infinitely without sacrificing image detail.
                         The user-perceived quality of a bitmap image is tied to the resolution at which
                         the bitmap is intended to be viewed.
               •   See “Creating a PDF Graphics Context.”
               • A window graphics context is a graphics context that you
                   can use to draw into a window. Note that because Quartz 2D is a graphics engine
                   and not a window management system, you use one of the application frameworks
                   to obtain a graphics context for a window. See “Creating a Window Graphics Context
                   in Mac OS X” for details.

               • A layer context (CGLayerRef) is an offscreen drawing
                   destination associated with another graphics context. It is designed for optimal
                   performance when drawing the layer to the graphics context that created it. A layer
                   context can be a much better choice for offscreen drawing than a bitmap graphics
                   context. See “Core Graphics Layer Drawing.”
Quartz 2D Opaque Data Types
                  Opaque Data Type




                  The opaque data types available in Quartz 2D include the following:
                   •   CGPathRef, used for vector graphics to create paths that you fill or stroke. See
                       “Paths.”
                   •   CGImageRef, used to represent bitmap images and bitmap image masks based on
                       sample data that you supply. See “Bitmap Images and Image Masks.”
                   •   CGLayerRef, used to represent a drawing layer that can be used for repeated
                       drawing (such as for backgrounds or patterns) and for offscreen drawing. See “Core
                       Graphics Layer Drawing”
                   •   CGPatternRef, used for repeated drawing. See “Patterns.”
                   •   CGShadingRef and CGGradientRef, used to paint gradients. See “Gradients.”
                   •   CGFunctionRef, used to define callback functions that take an arbitrary number of
                       floating-point arguments. You use this data type when you create gradients for a
                       shading. See “Gradients.”
                   •   CGColorRef and CGColorSpaceRef, used to inform Quartz how to interpret color.
                       See “Color and Color Spaces.”
                   •   CGImageSourceRef and CGImageDestinationRef, which you use to move data into
                       and out of Quartz. See “Data Management in Quartz 2D” and Image I/O
                       Programming Guide.
                   •   CGFontRef, used to draw text. See “Text.”
                   •   CGPDFDictionaryRef, CGPDFObjectRef, CGPDFPageRef, CGPDFStream,
                       CGPDFStringRef, and CGPDFArrayRef, which provide access to PDF metadata. See
                       “PDF Document Creation, Viewing, and Transforming.”
                   •   CGPDFScannerRef and CGPDFContentStreamRef, which parse PDF metadata. See
                       “PDF Document Parsing.”
                   •   CGPSConverterRef, used to convert PostScript to PDF. It is not available in iOS. See
                       “PostScript Conversion.”
Graphics States



               •   Graphics State
                     .

               •   Graphics Context   Graphics State

                                .

               •   CGContextSaveGState, CGContextRestoreGState
                                                 .
Graphics States

               Parameters that are associated with the graphics state

               •Current transformation matrix (CTM) : “Transforms”
               •Clipping area :“Paths”
               •Line: width, join, cap, dash, miter limit : “Paths”
               •Accuracy of curve estimation (flatness): “Paths”
               •Anti-aliasing setting: “Graphics Contexts”
               •Color: fill and stroke settings: “Color and Color Spaces”
               •Alpha value (transparency): “Color and Color Spaces”
               •Rendering intent : “Color and Color Spaces”
               •Color space: fill and stroke settings: “Color and Color Spaces”
               •Text: font, font size, character spacing, text drawing mode : “Text”
               •Blend mode : “Paths” and “Bitmap Images and Image Masks”
Creating a Bitmap Graphics Context



                 You use the function CGBitmapContextCreate to create a bitmap graphics context. This
                 function takes the following parameters:
                  •   data. Supply a pointer to the destination in memory where you want the drawing
                      rendered. The size of this memory block should be at least (bytesPerRow*height)
                      bytes.
                  •   width. Specify the width, in pixels, of the bitmap.
                  •   height. Specify the height, in pixels, of the bitmap.
                  •   bitsPerComponent. Specify the number of bits to use for each component of a
                      pixel in memory. For example, for a 32-bit pixel format and an RGB color space, you
                      would specify a value of 8 bits per component. See “Supported Pixel Formats.”
                  •   bytesPerRow. Specify the number of bytes of memory to use per row of the
                      bitmap.Tip:  When you create a bitmap graphics context, you’ll get the best
                      performance if you make sure the data and bytesPerRow are 16-byte aligned.



                  •   colorspace. The color space to use for the bitmap context. You can provide a Gray,
                      RGB, CMYK, or NULL color space when you create a bitmap graphics context. For
                      detailed information on color spaces and color management principles, see Color
                      Management Overview. For information on creating and using color spaces in
                      Quartz, see “Color and Color Spaces.” For information about supported color spaces,
                      see “Color Spaces and Bitmap Layout” in the “Bitmap Images and Image Masks”
                      chapter.
                  •   bitmapInfo. Bitmap layout information, expressed as a CGBitmapInfo constant,
                      that specifies whether the bitmap should contain an alpha component, the relative
                      location of the alpha component (if there is one) in a pixel, whether the alpha
                      component is premultiplied, and whether the color components are integer or
                      floating-point values.
Quartz 2D Coordinate Systems
Path
               path           Path
                   ,                 .
Path Building Block
               Points
               Points are x and y coordinates that specify a location in user space. You can call the
               function CGContextMoveToPoint to specify a starting position for a new subpath.

               Lines
               A line is defined by its endpoints. Its starting point is always assumed to be the current
               point, so when you create a line, you specify only its endpoint. You use the function
               CGContextAddLineToPoint to append a single line to a subpath.

               You can add a series of connected lines to a path by calling the function
               CGContextAddLines. You pass this function an array of points. The first point must be
               the starting point of the first line; the remaining points are endpoints. Quartz begins a
               new subpath at the first point and connects a straight line segment to each endpoint.

               Arcs
               Arcs are circle segments. Quartz provides two functions that create arcs. The function CGContextAddArc creates a curved
               segment from a circle.
Path Building Block
Curves          Figure 3-7  A cubic Bézier curve uses two control points




                                                                             You use the function CGContextAddCurveToPoint to
                                                                             append a cubic Bézier curve from the current point, using
                                                                             control points and an endpoint you specify.




               Figure 3-8  A quadratic Bézier curve uses one control point




                                                                                               You can append a quadratic Bézier curve from
                                                                                               the current point by calling the function
                                                                                               CGContextAddQuadCurveToPoint, and
                                                                                               specifying a control point and an endpoint.
Path Building Block

                 Ellipses :   CGContextAddEllipseInRect.



                Rectangles
                You can add a rectangle to the current path by calling the function CGContextAddRect. You supply a CGRect structure that
                contains the origin of the rectangle and its width and height.
Creating a Path


     •                      , CGContextBeginPath              .
     • CGContextMoveToPoint                                          .
     • When you want to close the current subpath within a path, call the function
       CGContextClosePath to connect a segment to the starting point of the
       subpath. Subsequent path calls begin a new subpath, even if you do not
       explicitly set a new starting point.
     • When you draw arcs, Quartz draws a line between the current point and the
       starting point of the arc.
     • Quartz routines that add ellipses and rectangles add a new closed subpath
       to the path.
     •                                 fill  stroke
         .                           .
       CGPathRef       CGMutablePathRef              .
Painting a Path
           You can paint the current path by stroking or filling or both.
           Stroking paints a line that straddles the path. Filling paints the
           area contained within the path.
Stroke
  Parameters that affect how Quartz strokes the current path   Functions for Stroking a Path
ParameterFunction to set parameter value                       Quartz provides the functions for stroking the current path. Some
Line width                                                     are convenience functions for stroking rectangles or ellipses.
CGContextSetLineWidth                                          Functions that stroke paths
Line join                                                      Function
CGContextSetLineJoin
                                                               CGContextStrokePath
Line cap
                                                               Strokes the current path.
CGContextSetLineCap
                                                               CGContextStrokeRect
Miter limit
                                                               Strokes the specified rectangle.
CGContextSetMiterLimit
                                                               CGContextStrokeRectWithWidth
Line dash pattern
                                                               Strokes the specified rectangle, using the specified line width.
CGContextSetLineDash
                                                               CGContextStrokeEllipseInRect
Stroke color space
                                                               Strokes an ellipse that fits inside the specified rectangle.
CGContextSetStrokeColorSpace
                                                               CGContextStrokeLineSegments:
Stroke color
                                                               Strokes a sequence of lines.
CGContextSetStrokeColorCGContextSetStrokeColorWithColor
                                                               CGContextDrawPath :
Stroke pattern
                                                               If you pass the constant kCGPathStroke, strokes the current
CGContextSetStrokePattern
                                                               path. See “Filling a Path” if you want to both fill and stroke a path.
Fill
                Functions that fill paths
               Function
               Description
               CGContextEOFillPath
               Fills the current path using the even-odd rule.
               CGContextFillPath
               Fills the current path using the nonzero winding number rule.
               CGContextFillRect
               Fills the area that fits inside the specified rectangle.
               CGContextFillRects
               Fills the areas that fits inside the specified rectangles.
               CGContextFillEllipseInRect
               Fills an ellipse that fits inside the specified rectangle.
               CGContextDrawPath
               Fills the current path if you pass kCGPathFill (nonzero winding number rule) or
               kCGPathEOFill (even-odd rule). Fills and strokes the current path if you pass
               kCGPathFillStroke or kCGPathEOFillStroke.
Color and Color Spaces

                User Space                  device color
                                   .

          Color :                color space
          Color Space:

                                             Table 4-1  Color values in different color spaces
                                             Values


                                             value          color space components
                                       240 degrees,                             Hue, saturation,
                                       100%, 100%          HSB                  brightness


                                       0, 0, 1             RGB                  Red, green, blue



                                       1, 1, 0, 0                               Cyan, magenta,
                                                           CMYK
                                                                                yellow, black



                                       1, 0, 0             BGR
                                                                                Blue, green, red
Creating Device-Independent Color Spaces
Creating Device Color Spaces


               Device color spaces are primarily used by iOS applications because other
               options are not available. In most cases, a Mac OS X application should use a
               generic color space instead of creating a device color space. However, some
               Quartz routines expect images with a device color space. For example, if you
               call CGImageCreateWithMask and specify an image as the mask, the image
               must be defined with the device gray color space.
               You create a device color space by using one of the following functions:
                • CGColorSpaceCreateDeviceGray for a device-dependent grayscale color
                  space.
                • CGColorSpaceCreateDeviceRGB for a device-dependent RGB color space.
                • CGColorSpaceCreateDeviceCMYK for a device-dependent CMYK color
                  space.
About Quartz Transformation Functions



     User Space
     translate(   ), rotate(  ), scale(   ,    )            .
     Graphic Context                               3
     CTM(Current Transformation Matrix)
                                          identity matrix
                        .
Transformation
               CGContextTranslateCTM (myContext, w/4, 0);

               CGContextScaleCTM (myContext, .25,   .5);

               CGContextRotateCTM (myContext, radians ( 22.));
Creating Affine Transforms
          The affine transform functions available in Quartz operate on matrices, not on the CTM.
          You can use these functions to construct a matrix that you later apply to the CTM by
          calling the function CGContextConcatCTM.




                            Affine transform functions for translation, rotation, and scaling
                            Functio
                            CGAffineTransformMakeTranslation
                            To construct a new translation matrix from x and y values that specify how much to move
                            the origin.
                            CGAffineTransformTranslate
                            To apply a translation operation to an existing affine transform.
                            CGAffineTransformMakeRotation
                            To construct a new rotation matrix from a value that specifies in radians how much to
                            rotate the coordinate system.
                            CGAffineTransformRotate
                            To apply a rotation operation to an existing affine transform.
                            CGAffineTransformMakeScale
                            To construct a new scaling matrix from x and y values that specify how much to stretch
                            or shrink coordinates.
                            CGAffineTransformScale
                            To apply a scaling operation to an existing affine transform.
•               C API

                   ✴               Create                    CGContextRelese(Context)                       .

                   ✴               Get                                                  .


               •
                   ✴       :

                   ✴   :                                                                                .


               •
                   ✴           ,                                          CGColorSpaceCreateDeviceRGB


               •
                   ✴                       Affine Transform                         /        ,   ,   ,
                                       .
UIResponder Class
          Managing the Responder Chain
               1   – nextResponder
               2   – isFirstResponder                  motionBegan:withEvent:
               3   – canBecomeFirstResponder           Tells the receiver that a motion event has begun.
               4   – becomeFirstResponder
                                                       - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
               5   – canResignFirstResponder
               6   – resignFirstResponder              Parameters
                                                       motion
          Managing Input Views                         An event-subtype constant indicating the kind of motion. A common motion is shaking,
               1     inputView  property               which is indicated by UIEventSubtypeMotionShake.
               2     inputAccessoryView  property
                                                       event
               3   – reloadInputViews
                                                       An object representing the event associated with the motion.
          Responding to Touch Events                   Discussion
               1   – touchesBegan:withEvent:           iOS informs the first responder only when a motion event starts and when it ends; for
               2   – touchesMoved:withEvent:           example, it doesn’t report individual shakes. The receiving object must be the first
               3   – touchesEnded:withEvent:           responder to receive motion events.
               4   – touchesCancelled:withEvent:
          Responding to Motion Events                  The default implementation of this method does nothing. However immediate UIKit
                                                       subclasses of UIResponder, particularly UIView, forward the message up the responder
               1   – motionBegan:withEvent:
                                                       chain.
               2   – motionEnded:withEvent:
               3   – motionCancelled:withEvent:
          Responding to Remote-Control Events
               1   – remoteControlReceivedWithEvent:
          Getting the Undo Manager
               1     undoManager  property
          Validating Commands
               1   – canPerformAction:withSender:
UITouch Class
                                                         gestureRecognizers
                                                         The gesture recognizers that are receiving the touch object.
               Getting the Location of Touches           @property(nonatomic,readonly,copy) NSArray *gestureRecognizers
                1   – locationInView:                    Discussion
                2   – previousLocationInView:            The objects in the array are instances of a subclass of the abstract base class
                3     view  property                     UIGestureRecognizer. If there are no gesture recognizers currently receiving the touch
                4     window  property                   objects, this property holds an empty array.
               Getting Touch Attributes
                1     tapCount  property
                2     timestamp  property
                3     phase  property
               Getting a Touch Object’s Gesture Recognizers
                1     gestureRecognizers  property


                                                     previousLocationInView:
                                                     Returns the previous location of the receiver in the coordinate system of the given view.

                                                     - (CGPoint)previousLocationInView:(UIView *)view


                                                     locationInView:
                                                     Returns the current location of the receiver in the coordinate system of the given view.

                                                     - (CGPoint)locationInView:(UIView *)view
UIEvent
                                            UIEvent Class                                   subtype
                                                                                            Returns the subtype of the event. (read-only)
-
                                                                                            @property(readonly) UIEventSubtype subtype
-                                                                                           Discussion
                                                                                            The UIEventSubtype constant returned by this property indicates the
-                        :                                        /     ,                   subtype of the event in relation to the general type, which is returned
                                                                                            from the type property.

                                                            Responder                   .   typedef enum {
                                                                                               UIEventSubtypeNone                                          =   0,
                                            ,       ,   ,                                      UIEventSubtypeMotionShake                                   =   1,
     .                                                                                         UIEventSubtypeRemoteControlPlay                             =   100,
                                                                                               UIEventSubtypeRemoteControlPause                            =   101,
                                                                  shake       remote-
                                                                                               UIEventSubtypeRemoteControlStop                             =   102,
control                          play, previous track                                   .      UIEventSubtypeRemoteControlTogglePlayPause                  =   103,
motionBegan:withEvent: , remoteControlReceivedWithEvent:                                       UIEventSubtypeRemoteControlNextTrack                        =   104,
                                                                                               UIEventSubtypeRemoteControlPreviousTrack                    =   105,
                                                                                               UIEventSubtypeRemoteControlBeginSeekingBackward             =   106,
                                                                                               UIEventSubtypeRemoteControlEndSeekingBackward               =   107,
Getting the Touches for an Event                                                               UIEventSubtypeRemoteControlBeginSeekingForward              =   108,
 1       – allTouches                                                                          UIEventSubtypeRemoteControlEndSeekingForward                =   109,
 2       – touchesForView:                                                                  } UIEventSubtype;
 3       – touchesForWindow:
Getting Event Attributes                                                                    type
 1         timestamp  property                                                              Returns the type of the event. (read-only)
Getting the Event Type
                                                                                            @property(readonly) UIEventType type
 1         type  property
 2         subtype  property
                                                                                            typedef enum {
Getting the Touches for a Gesture Recognizer                                                   UIEventTypeTouches,
 1       – touchesForGestureRecognizer:                                                        UIEventTypeMotion,
                                                                                               UIEventTypeRemoteControl,
                             allTouches                                                     } UIEventType;
                             Returns all touch objects associated with the receiver.

                             - (NSSet *)allTouches
                             Return Value
                             A set of UITouch objects representing all touches associated with an event (represented by the receiver).

                             Discussion
          	    	    	        If the touches of the event originate in different views and windows, the UITouch objects obtained from this
CGColor

               CGColorGetComponents
               Returns the values of the color components (including alpha) associated with a Quartz
               color.

               const CGFloat * CGColorGetComponents (
                   CGColorRef color
               );
               Parameters
               color
               A Quartz color.
               Return Value
               An array of intensity values for the color components (including alpha) associated with the
               specified color. The size of the array is one more than the number of components of the
               color space for the color.
UIColor
Tasks
Creating a UIColor Object from Component Values
 1        + colorWithWhite:alpha:                        CGColor
 2        + colorWithHue:saturation:brightness:alpha:    The Quartz color reference that corresponds to the receiver’s color. (read-o
 3        + colorWithRed:green:blue:alpha:
 4        + colorWithCGColor:                            @property(nonatomic,readonly) CGColorRef CGColor
 5        + colorWithPatternImage:
 6        – colorWithAlphaComponent:
Initializing a UIColor Object
 1        – initWithWhite:alpha:
 2        – initWithHue:saturation:brightness:alpha:    System Colors
 3        – initWithRed:green:blue:alpha:                1   + lightTextColor
 4        – initWithCGColor:                             2   + darkTextColor
 5        – initWithPatternImage:                        3   + groupTableViewBackgroundColor
Creating a UIColor with Preset Component Values          4   + viewFlipsideBackgroundColor
 1        + blackColor                                   5   + scrollViewTexturedBackgroundColor
 2        + darkGrayColor                               Retrieving Color Information
 3        + lightGrayColor                               1     CGColor  property
 4        + whiteColor
 5        + grayColor
                                                        Drawing Operations
 6        + redColor                                     1   – set
 7        + greenColor                                   2   – setFill
 8        + blueColor                                    3   – setStroke
 9        + cyanColor
 10       + yellowColor
 11       + magentaColor
 12       + orangeColor
 13       + purpleColor
 14       + brownColor
 15       + clearColor
View Animation


               beginAnimations:context:
               Marks the beginning of a begin/commit animation block.

               + (void)beginAnimations:(NSString *)animationID context:(void *)context
               Parameters
               animationID
               An application-supplied identifier for the animations.
               context
               Custom data that you want to associate with this set of animations. information that is
               passed to the animation delegate messages—the selectors set using the
               setAnimationWillStartSelector: and setAnimationDidStopSelector: methods.
               Discussion
               Use of this method is discouraged in iOS 4.0 and later. You should use the block-based
               animation methods to specify your animations instead.

               This method signals to the system that you want to specify the beginning of an animation
               block. After calling this method, your application should configure the animation options
               (using the setAnimation class methods) and then change the desired animatable
               properties of your views. When you are done changing your view properties, call the
               commitAnimations method to close the set and schedule the animations.

               You can nest sets of animations (by calling this method again before committing a
               previous set of animations) as needed. Nesting animations groups them together and
               allows you to set different animation options for the nested group.

               If you install a start or stop selector using the setAnimationWillStartSelector: or
               setAnimationDidStopSelector: method, the values you specify for the animationID
               and context parameters are passed to your selectors at runtime. You can use these
               parameters to pass additional information to those selectors.
View Animation

     setAnimationTransition:forView:cache:
     Sets a transition to apply to a view during an animation block.

     + (void)setAnimationTransition:(UIViewAnimationTransition)transition forView:(UIView *)view cache:(BOOL)cache
     Parameters
     transition
     A transition to apply to view. Possible values are described in UIViewAnimationTransition.
     view
     The view to apply the transition to.
     cache
     If YES, the before and after images of view are rendered once and used to create the frames in the animation. Caching can improve
     performance but if you set this parameter to YES, you must not update the view or its subviews during the transition. Updating the view and its
     subviews may interfere with the caching behaviors and cause the view contents to be rendered incorrectly (or in the wrong location) during the
     animation. You must wait until the transition ends to update the view.
     If NO, the view and its contents must be updated for each frame of the transition animation, which may noticeably affect the frame rate.
     Discussion
     Use of this method is discouraged in iOS 4.0 and later. You should use the
     transitionWithView:duration:options:animations:completion: method to perform transitions instead.

     If you want to change the appearance of a view during a transition—for example, flip from one view to another—then use a container view, an
     instance of UIView, as follows:

      1.    Begin an animation block.
      2.    Set the transition on the container view.
      3.    Remove the subview from the container view.
      4.    Add the new subview to the container view.
      5.    Commit the animation block.
View Animation

               commitAnimations
               Marks the end of a begin/commit animation block and schedules the animations for
               execution.

               + (void)commitAnimations
               Discussion
               Use of this method is discouraged in iOS 4.0 and later. You should use the block-based
               animation methods to specify your animations instead.

               If the current animation set is the outermost set, this method starts the animations when
               the application returns to the run loop. If the current animation set is nested inside
               another set, this method waits until the outermost set of animations is committed, at
               which point it commits all of the animations together.

               Animations run in a separate thread to avoid blocking the application. In this way,
               multiple animations can be piled on top of one another. See
               setAnimationBeginsFromCurrentState: for how to start animations while others are in
               progress.
PickerView Class
                 Tasks
                 Getting the Dimensions of the View Picker
                  1     numberOfComponents  property
                  2   – numberOfRowsInComponent:
                  3   – rowSizeForComponent:
                 Reloading the View Picker
                  1   – reloadAllComponents
                  2   – reloadComponent:
                 Selecting Rows in the View Picker
                  1   – selectRow:inComponent:animated:
                  2   – selectedRowInComponent:
                 Returning the View for a Row and Component
                  1   – viewForRow:forComponent:
                 Specifying the Delegate
                  1     delegate  property
                 Specifying the Data Source
                  1     dataSource  property
                 Managing the Appearance of the Picker View
                  1     showsSelectionIndicator  property
PickerView DataSource Protocol
     Tasks
     Providing Counts for the Picker View
          1   – numberOfComponentsInPickerView:
          2   – pickerView:numberOfRowsInComponent:



                                   numberOfComponentsInPickerView:
                                   Called by the picker view when it needs the number of components. (required)

                                   - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
                                   Parameters
                                   pickerView
                                   The picker view requesting the data.
                                   Return Value
                                   The number of components (or “columns”) that the picker view should display.



                                   pickerView:numberOfRowsInComponent:
                                   Called by the picker view when it needs the number of rows for a specified component.
                                   (required)

                                   - (NSInteger)pickerView:(UIPickerView *)pickerView
                                   numberOfRowsInComponent:(NSInteger)component
                                   Parameters
                                   pickerView
                                   The picker view requesting the data.
                                   component
                                   A zero-indexed number identifying a component of pickerView. Components are
                                   numbered left-to-right.
PickerView Delegate Protocol
Setting the Dimensions of the Picker View
 1   – pickerView:rowHeightForComponent:                                                   pickerView:titleForRow:forComponent:
 2   – pickerView:widthForComponent:                                                       Called by the picker view when it needs the title to use
Setting the Content of Component Rows                                                      for a given row in a given component.
The methods in this group are marked @optional. However, to use a picker view, you         - (NSString *)pickerView:(UIPickerView *)
must implement either the pickerView:titleForRow:forComponent: or the                      pickerView titleForRow:(NSInteger)row
pickerView:viewForRow:forComponent:reusingView: method to provide the content              forComponent:(NSInteger)component
of component rows.                                                                         Parameters
                                                                                           pickerView
 1   – pickerView:titleForRow:forComponent:
                                                                                           An object representing the picker view requesting the
 2   – pickerView:viewForRow:forComponent:reusingView:
                                                                                           data.
Responding to Row Selection                                                                row
 1   – pickerView:didSelectRow:inComponent:                                                A zero-indexed number identifying a row of component.
                                                                                           Rows are numbered top-to-bottom.
pickerView:viewForRow:forComponent:reusingView:                                            component
Called by the picker view when it needs the view to use for a given row in a given         A zero-indexed number identifying a component of
component.                                                                                 pickerView. Components are numbered left-to-right.
                                                                                           Return Value
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)
                                                                                           The string to use as the title of the indicated component
row forComponent:(NSInteger)component reusingView:(UIView *)view
                                                                                           row.
Parameters
pickerView
An object representing the picker view requesting the data.
row
A zero-indexed number identifying a row of component. Rows are numbered top-to-
bottom.
component
A zero-indexed number identifying a component of pickerView. Components are
numbered left-to-right.
view
A view object that was previously used for this row, but is now hidden and cached by the
picker view.
Return Value
A view object to use as the content of row. The object can be any subclass of UIView,
such as UILabel, UIImageView, or even a custom view.
NSDictionary Class
               initWithObjects:forKeys:
               Initializes a newly allocated dictionary with entries constructed from the contents of the
               objects and keys arrays.

               - (id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys
               Parameters
               objects
               An array containing the values for the new dictionary.
               keys
               An array containing the keys for the new dictionary. Each key is copied (using
               copyWithZone:; keys must conform to the NSCopying protocol), and the copy is added
               to the new dictionary.
               Discussion
               This method steps through the objects and keys arrays, creating entries in the new
               dictionary as it goes. An NSInvalidArgumentException is raised if the objects and keys
               arrays do not have the same number of elements.



               allKeys
               Returns a new array containing the dictionary’s keys.

               - (NSArray *)allKeys
               Return Value
               A new array containing the dictionary’s keys, or an empty array if the dictionary has no
               entries.

               Discussion
               The order of the elements in the array is not defined.
UIAlertView Class

               initWithTitle:message:delegate:cancelButtonTitle:otherButton
               Titles:
               Convenience method for initializing an alert view.

               - (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:
               (id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle
               otherButtonTitles:(NSString *)otherButtonTitles, ...
               Parameters
               title
               The string that appears in the receiver’s title bar.
               message
               Descriptive text that provides more details than the title.
                                                                                                 show
                                                                                                 Displays the receiver using animation.
               delegate
               The receiver’s delegate or nil if it doesn’t have a delegate.                     - (void)show
               cancelButtonTitle
               The title of the cancel button or nil if there is no cancel button.
               Using this argument is equivalent to setting the cancel button index to the value returned
               by invoking addButtonWithTitle: specifying this title.
               otherButtonTitles,
               The title of another button.
               Using this argument is equivalent to invoking addButtonWithTitle: with this title to add
               more buttons.
               ...
               Titles of additional buttons to add to the receiver, terminated with nil.
               Return Value
               Newly initialized alert view.
UIAlertViewDelegate Protocol Reference


                   alertView:clickedButtonAtIndex:
                   Sent to the delegate when the user clicks a button on an alert view.

                   - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:
                   (NSInteger)buttonIndex
                   Parameters
                   alertView
                   The alert view containing the button.
                   buttonIndex
                   The position of the clicked button. The button indices start at 0.
                   Discussion
                   The receiver is automatically dismissed after this method is invoked.
#import "SimpleSketchAppDelegate.h"
               #import "CanvasView.h"

               @implementation SimpleSketchAppDelegate


               @synthesize window=_window;

               - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)
               launchOptions
               {
                   // Override point for customization after application launch.
                   CanvasView *aCanvasView = [[CanvasView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
                   aCanvasView.backgroundColor = [UIColor darkGrayColor];

                   [self.window addSubview:aCanvasView];

                   [self.window makeKeyAndVisible];
                   return YES;
               }
CanvasView.m
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

            CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
            cgContext = CGBitmapContextCreate(NULL, frame.size.width, frame.size.height, 8, 4*frame.size.width, colorSpace, kCGImageAlphaPremultipliedFirst);
            CGColorSpaceRelease(colorSpace);

            CGContextSetLineWidth(cgContext, 25);
            CGContextSetLineCap(cgContext, kCGLineCapRound);
            CGContextSetRGBStrokeColor(cgContext, 1.0, 1.0, 1.0, 1.0);
    }
    return self;
}




                                                                    CanvasView.h
                                                                @interface CanvasView : UIView {

                                                                     CGContextRef cgContext;

                                                                }

                                                                @end
CGColorSpaceCreateDeviceRGB
                             Creates a device-dependent RGB color space.

                             CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void);
                             Return Value
                             A device-dependent RGB color space. You are responsible for releasing this object by
                             calling CGColorSpaceRelease. If unsuccessful, returns NULL.


CGBitmapContextCreate
Creates a bitmap graphics context.

CGContextRef CGBitmapContextCreate (
   void *data,
   size_t width,
   size_t height,
   size_t bitsPerComponent,
   size_t bytesPerRow,
   CGColorSpaceRef colorspace,
   CGBitmapInfo bitmapInfo
);
Parameters
data
A pointer to the destination in memory where the drawing is to be rendered. The size of this memory block should be at least
(bytesPerRow*height) bytes. You can pass NULL if you want Quartz to allocate memory for the bitmap. This frees you from managing your own
memory, which reduces memory leak issues.
width : The width, in pixels, of the required bitmap.
height : The height, in pixels, of the required bitmap.
bitsPerComponent : The number of bits to use for each component of a pixel in memory. For example, for a 32-bit pixel format and an RGB color
space, you would specify a value of 8 bits per component. For the list of supported pixel formats, see “Supported Pixel Formats” in the “Graphics
Contexts” chapter of Quartz 2D Programming Guide.
bytesPerRow : The number of bytes of memory to use per row of the bitmap.
colorspace : The color space to use for the bitmap context. Note that indexed color spaces are not supported for bitmap graphics contexts.
bitmapInfo
Constants that specify whether the bitmap should contain an alpha channel, the alpha channel’s relative location in a pixel, and information about
whether the pixel components are floating-point or integer values. The constants for specifying the alpha channel information are declared with the
CGImageAlphaInfo type but can be passed to this parameter safely. You can also pass the other constants associated with the CGBitmapInfo type.
(See CGImage Reference for a description of the CGBitmapInfo and CGImageAlphaInfo constants.)
For an example of how to specify the color space, bits per pixel, bits per pixel component, and bitmap information using the
CGBitmapContextCreate function, see “Creating a Bitmap Graphics Context” in the “Graphics Contexts” chapter of Quartz 2D Programming Guide.
Return Value
A new bitmap context, or NULL if a context could not be created. You are responsible for releasing this object using CGContextRelease.
initWithFrame:
                     Initializes and returns a newly allocated view object with the specified frame rectangle.
     View
                     - (id)initWithFrame:(CGRect)aRect
                     Parameters
                     aRect
                     The frame rectangle for the view, measured in points. The origin of the frame is relative
                     to the superview in which you plan to add it. This method uses the frame rectangle to set
                 .
                     the center and bounds properties accordingly.
                     Return Value
                     An initialized view object or nil if the object couldn't be created.

                     Discussion
                     The new view object must be inserted into the view hierarchy of a window before it can be
                     used. If you create a view object programmatically, this method is the designated
                     initializer for the UIView class. Subclasses can override this method to perform any
                     custom initialization but must call super at the beginning of their implementation.

                     If you use Interface Builder to design your interface, this method is not called when your
                     view objects are subsequently loaded from the nib file. Objects in a nib file are
                     reconstituted and then initialized using their initWithCoder: method, which modifies
                     the attributes of the view to match the attributes stored in the nib file. For detailed
                     information about how views are loaded from a nib file, see Resource Programming
                     Guide.
UIView Class   UIResponder Class
          UIResponder
                         .
          -(void)touchesBegan:(NSSet *) touches withEvent:(UIEvent *)event
          -(void)touchesMoved:(NSSet *) touches withEvent:(UIEvent *)event
          -(void)touchesEnded:(NSSet *) touches withEvent:(UIEvent *)event

                           touchesBegan:
                                                  touchesMoved
                .
                                             touchesEnded:             .
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
     {
         UITouch *touch;

         for (touch in touches) {
             CGPoint location = [touch locationInView:self];
             CGPoint preLocation = [touch previousLocationInView:self];
             NSLog(@"PrevLoc = %@, Loc = %@", NSStringFromCGPoint(preLocation),
     NSStringFromCGPoint(location));                                                            cgContext

                       CGContextBeginPath(cgContext);                                                 preLocation
                       CGContextMoveToPoint(cgContext, preLocation.x, preLocation.y);
                       CGContextAddLineToPoint(cgContext, location.x, location.y);
                       CGContextStrokePath(cgContext);                                                  Location
              }

              [self setNeedsDisplay];
     }



                                                                                        CanvasView

                                                                                               -drawRect:
- (void)drawRect:(CGRect)rect                                     UIGraphicsGetCurrentContext
{                                                                 Returns the current graphics context.
    // Drawing code
    CGRect bounds = [self bounds];                                CGContextRef UIGraphicsGetCurrentContext (
    CGContextRef context = UIGraphicsGetCurrentContext();
                                                                     void
     CGImageRef image = CGBitmapContextCreateImage(cgContext);    );
     CGContextDrawImage(context, bounds, image);                  Return Value
     CGImageRelease(image);                                       The current graphics context.
}
                                                                  Discussion
                                                                  The current graphics context is nil by default. Prior to calling its drawRect:
                                                                  method, view objects push a valid context onto the stack, making it current. If
CGContextDrawImage                                                you are not using a UIView object to do your drawing, however, you must push a
Draws an image into a graphics context.                           valid context onto the stack manually using the UIGraphicsPushContext
                                                                  function.
void CGContextDrawImage (
   CGContextRef c,                                                You should call this function from the main thread of your application only.
   CGRect rect,
   CGImageRef image
);                                                     CGBitmapContextCreateImage
Parameters                                             Creates and returns a Quartz image from the pixel data in a bitmap graphics context.
c
                                                       CGImageRef CGBitmapContextCreateImage (
The graphics context in which to draw the image.
                                                           CGContextRef c
rect                                                   );
The location and dimensions in user space of the       Parameters
bounding box in which to draw the image.               c
image                                                  A bitmap graphics context.
The image to draw.                                     Return Value
Discussion                                             A CGImage object that contains a snapshot of the bitmap graphics context or NULL if the image
Quartz scales the image—disproportionately, if         is not created.
necessary—to fit the bounds specified by the rect
                                                       Discussion
parameter.
                                                       The CGImage object returned by this function is created by a copy operation. Subsequent
                                                       changes to the bitmap graphics context do not affect the contents of the returned image. In
                                                       some cases the copy operation actually follows copy-on-write semantics, so that the actual
                                                       physical copy of the bits occur only if the underlying data in the bitmap graphics context is
                                                       modified. As a consequence, you may want to use the resulting image and release it before you
                                                       perform additional drawing into the bitmap graphics context. In this way, you can avoid the
                                                       actual physical copy of the data.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
               (NSDictionary *)launchOptions
               {
                   // Override point for customization after application launch.
                   CanvasView *aCanvasView = [[CanvasView alloc] initWithFrame:CGRectMake(0, 0, 320,
               480)];
                   aCanvasView.backgroundColor = [UIColor darkGrayColor];

                   aCanvasView.multipleTouchEnabled = YES;

                   [self.window addSubview:aCanvasView];
                   [self.window makeKeyAndVisible];
                   return YES;
               }




                                                                                                       .
•
                                (   )

               • CGLayer
                   (       ),
@interface CanvasView : UIView {




                                                                        CGLayer
              CGContextRef cgContext;
              CGLayerRef cgLayer;

     }

     @end

 - (id)initWithFrame:(CGRect)frame
 {
     self = [super initWithFrame:frame];
     if (self) {
         // Initialization code

         CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
         cgContext = CGBitmapContextCreate(NULL, frame.size.width, frame.size.height,
 8, 4*frame.size.width, colorSpace, kCGImageAlphaPremultipliedFirst);
         CGColorSpaceRelease(colorSpace);

                  cgLayer = CGLayerCreateWithContext(cgContext, frame.size, NULL);
                  CGContextRef context = CGLayerGetContext(cgLayer);
                  CGContextSetLineWidth(context, 25);
                  CGContextSetLineCap(context, kCGLineCapRound);
                  CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
              }
              return self;
 }

 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
                                                                                     - (void)drawRect:(CGRect)rect
 {
                                                                                     {
     UITouch *touch;
                                                                                         // Drawing code
                                                                                         CGRect bounds = [self bounds];
     for (touch in touches) {
                                                                                         CGContextRef context = UIGraphicsGetCurrentContext();
         CGPoint location = [touch locationInView:self];
         CGPoint preLocation = [touch previousLocationInView:self];
                                                                                         CGImageRef image = CGBitmapContextCreateImage(cgContext);
         NSLog(@"PrevLoc = %@, Loc = %@", NSStringFromCGPoint(preLocation),
                                                                                         CGContextDrawImage(context, bounds, image);
 NSStringFromCGPoint(location));
                                                                                         CGImageRelease(image);
                  CGContextRef context = CGLayerGetContext(cgLayer);
                                                                                         CGContextSetAlpha(context, 0.7);
                  CGContextBeginPath(context);
                                                                                         CGContextDrawLayerInRect(context, bounds, cgLayer);
                  CGContextMoveToPoint(context, preLocation.x, preLocation.y);
                                                                                     }
                  CGContextAddLineToPoint(context, location.x, location.y);
                  CGContextStrokePath(context);
              }

              [self setNeedsDisplay];
 }

 - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
 {                                                                                                          0.7
     CGRect bounds = [self bounds];

              CGContextSetAlpha(cgContext, 0.7);
              CGContextDrawLayerInRect(cgContext, bounds, cgLayer);
              CGContextClearRect(CGLayerGetContext(cgLayer), bounds);

              [self setNeedsDisplay];
 }
CGContextDrawLayerInRect
                                                                           Draws the contents of a CGLayer object into the specified rectangle.

                                                                           void CGContextDrawLayerInRect (
                                                                              CGContextRef context,
                                                                              CGRect rect,
                                                                              CGLayerRef layer
                                                                           );
                                                                           Parameters
                                                                           context
                                                                           The graphics context associated with the layer.
                                                                           rect
                                                                           The rectangle, in current user space coordinates, to draw to.
                                                                           layer
                                                                           The layer whose contents you want to draw.
                                                                           Discussion
                                                                           The contents are scaled, if necessary, to fit into the rectangle.



CGContextSetAlpha
Sets the opacity level for objects drawn in a graphics context.

void CGContextSetAlpha (
   CGContextRef c,
   CGFloat alpha
);
Parameters
c
The graphics context for which to set the current graphics state’s alpha value parameter.
alpha
A value that specifies the opacity level. Values can range from 0.0 (transparent) to 1.0 (opaque). Values outside this
range are clipped to 0.0 or 1.0.
Discussion
This function sets the alpha value parameter for the specified graphics context. To clear the contents of the drawing
canvas, use CGContextClearRect.
CGLayerCreateWithContext
Creates a CGLayer object that is associated with a graphics context.

CGLayerRef CGLayerCreateWithContext (
    CGContextRef context,
    CGSize size,
    CFDictionaryRef auxiliaryInfo
);
Parameters
context
The graphics context you want to create the layer relative to. The
layer uses this graphics context as a reference for initialization.
size
The size, in default user space units, of the layer relative to the
                                                                       CGContextClearRect
                                                                       Paints a transparent rectangle.
graphics context.
auxiliaryInfo                                                          void CGContextClearRect (
Reserved for future use. Pass NULL.                                       CGContextRef c,
                                                                          CGRect rect
Return Value                                                           );
A CGLayer object. You are responsible for releasing this object        Parameters
using the function CGLayerRelease when you no longer need the          c
layer.                                                                 The graphics context in which to paint the rectangle.
                                                                       rect
CGLayerGetContext                                                      The rectangle, in user space coordinates.
Returns the graphics context associated with a CGLayer object.
                                                                       Discussion
CGContextRef CGLayerGetContext (
    CGLayerRef layer                                                   If the provided context is a window
);
Parameters                                                             or bitmap context, Quartz effectively
layer
The layer whose graphics context you want to obtain.
                                                                       clears the rectangle. For other context types,
                                                                       Quartz fills the rectangle in a device-dependent manner. However,
Return Value                                                           you should not use this function in contexts other than window or
The graphics context associated with the layer.                        bitmap contexts.

Discussion
The context that’s returned is the context for the layer itself, not
the context that you specified when you created the layer.
Shake
                     UI             &
           KVO



          KVO
                          UI   IB


                 .
KVO
     @interface CanvasView : UIView {

              CGContextRef cgContext;
              CGLayerRef cgLayer;

              int strokeSize;
              float strokeAlpha;
              UIColor *strokeColor;

     }

     @property int strokeSize;
     @property float strokeAlpha;
     @property (retain) UIColor *strokeColor;

     - (id)initWithFrame:(CGRect)frame
     {
         self = [super initWithFrame:frame];
         if (self) {
             // Initialization code

                      [self addObserver:self forKeyPath:@"strokeColor" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
                      [self addObserver:self forKeyPath:@"strokeSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

             CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
             cgContext = CGBitmapContextCreate(NULL, frame.size.width, frame.size.height, 8, 4*frame.size.width, colorSpace,
     kCGImageAlphaPremultipliedFirst);
             CGColorSpaceRelease(colorSpace);

                      cgLayer = CGLayerCreateWithContext(cgContext, frame.size, NULL);
                      CGContextRef context = CGLayerGetContext(cgLayer);
                      // CGContextSetLineWidth(context, 25);
                      CGContextSetLineCap(context, kCGLineCapRound);
                      // CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
              }
              return self;
     }



     - (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
     {
         if ([keyPath isEqualToString:@"strokeColor"]) {
             [self updateStrokeColor];
         } else if( [keyPath isEqualToString:@"strokeSize"]) {
             [self updateStrokeSize];
         }
     }
@interface CanvasView (Private)

          -(void) updateStrokeColor;
          -(void) updateStrokeSize;                             CanvasView.m       @implementation
          @end


          - (void) updateStrokeColor {
              CGContextRef context = CGLayerGetContext(cgLayer);
              CGFloat *colors = (CGFloat *) CGColorGetComponents(self.strokeColor.CGColor);
              CGContextSetRGBStrokeColor(context, colors[0], colors[1], colors[2], colors[3]);
          }

          - (void) updateStrokeSize
          {
              CGContextRef context = CGLayerGetContext(cgLayer);
              CGContextSetLineWidth(context, self.strokeSize);
          }


          - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)
          launchOptions
          {
              // Override point for customization after application launch.
              CanvasView *aCanvasView = [[CanvasView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
              aCanvasView.backgroundColor = [UIColor darkGrayColor];

                   aCanvasView.multipleTouchEnabled = YES;
                   aCanvasView.strokeSize = 15;
                   aCanvasView.strokeColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1];
                   aCanvasView.strokeAlpha = 0.7;

                   [self.window addSubview:aCanvasView];
                   [self.window makeKeyAndVisible];
                   return YES;
          }
UI
                    (stroke size, alpha, color)
#import <UIKit/UIKit.h>

     @class CanvasView;

     @interface SimpleSketchAppDelegate : NSObject <UIApplicationDelegate> {

              CanvasView *aCanvasView;
              UIView *settingView;
              UIPickerView *strokeColorPicker;
              UISlider *strokeSizeSlider;
              UISlider *strokeAlphaSlider;

     }

     -(IBAction) strokeSizeChanged: (id) sender;
     -(IBAction) strokeAlphaChanged:(id)sender;

     @property      (nonatomic,   retain)   IBOutlet   UIWindow *window;
     @property      (nonatomic,   retain)   IBOutlet   UIView *settingView;
     @property      (nonatomic,   retain)   IBOutlet   UIPickerView *strokeColorPicker;
     @property      (nonatomic,   retain)   IBOutlet   UISlider *strokeSizeSlider;
     @property      (nonatomic,   retain)   IBOutlet   UISlider *strokeAlphaSlider;

                                  @implementation SimpleSketchAppDelegate
     @end
                                  @synthesize   window=_window;
                                  @synthesize   settingView;
                                  @synthesize   strokeSizeSlider;
                                  @synthesize   strokeAlphaSlider;
                                  @synthesize   strokeColorPicker;

                                  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)
                                  launchOptions
                                  {
                                      // Override point for customization after application launch.
                                      aCanvasView = [[CanvasView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; //
                                      aCanvasView.backgroundColor = [UIColor darkGrayColor];

                                      aCanvasView.multipleTouchEnabled = YES;
                                      aCanvasView.strokeSize = 15;
                                      aCanvasView.strokeColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1];
                                      aCanvasView.strokeAlpha = 0.7;

                                      [self.window addSubview:aCanvasView];
                                      [self.window makeKeyAndVisible];
                                      return YES;
                                  }


                                  -(IBAction) strokeSizeChanged: (id) sender;
                                  {

                                  }
	        	     	                  -(IBAction) strokeAlphaChanged:(id)sender
PickerView




                        - (NSInteger) numberOfComponentsInPickerView:(UIPickerView *) pickerView
                                                          .

                        - (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowInComponent:(NSInteger) component
                                                            .



                        -(NSString *) pickerView: (UIPickerView *)pickerView titleForRow:(NSInteger) row forComponent:(NSInteger)
                        component
                                                                                    .

                        -(UIView *) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)
                        component reusingView:(UIView *)view
                                                                             .

                        -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
-(NSDictionary *) colorDictionary
{
    if (colorDictionary != nil) {
        return colorDictionary;
    }

        UIColor     *MidNightColor = [UIColor colorWithRed:0 green:0 blue:0.5 alpha:1];
        UIColor     *TealColor = [UIColor colorWithRed:0 green:0.5 blue:0.5 alpha:1];
        UIColor     *LeadColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1];
        UIColor     *CloverColor = [UIColor colorWithRed:0 green:0.5 blue:0 alpha:1];
        UIColor     *CayenneColor = [UIColor colorWithRed:0.5 green:0 blue:0 alpha:1];
        UIColor     *AsparagusColor = [UIColor colorWithRed:0.5 green:0.5 blue:0 alpha:1];
        UIColor     *MaroonColor = [UIColor colorWithRed:0.5 green:0 blue:0.25 alpha:1];
        UIColor     *SnowColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1];

    NSArray *colorObjects = [NSArray arrayWithObjects:MidNightColor,TealColor,LeadColor,CloverColor,CayenneColor,AsparagusColor,MaroonColor, SnowColor,
nil];

        NSArray *colorKeys = [NSArray arrayWithObjects:@"Midnight", @"Teal", @"Lead", @"Clover",@"Cayenne", @"Asparagus", @"Maroon", @"Snow", nil];

        colorDictionary = [[NSDictionary alloc] initWithObjects:colorObjects forKeys:colorKeys];

        return colorDictionary;
}


    @class CanvasView;

    @interface SimpleSketchAppDelegate : NSObject <UIApplicationDelegate> {

          CanvasView *aCanvasView;
          UIView *settingView;
          UIPickerView *strokeColorPicker;
          UISlider *strokeSizeSlider;
          UISlider *strokeAlphaSlider;
          NSDictionary *colorDictionary;

    }
-(NSInteger) numberOfComponentsInPickerView:(UIPickerView *) pickerView
               {
                   return 1;
               }

               - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
               {
                   return [[self.colorDictionary allKeys] count];
               }


               -(UIView *) pickerView: (UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component
               reusingView:(UIView *) view
               {
                   NSString *keyForTheColor = [[self.colorDictionary allKeys] objectAtIndex:row];
                   UIColor *theColor = [self.colorDictionary valueForKey:keyForTheColor];
                   UIView *returnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 30)];
                   UIView *colorView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, 24, 24)];

                   colorView.backgroundColor = theColor;
                   UILabel *colorNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, 250, 24)];
                   colorNameLabel.backgroundColor = [UIColor clearColor];
                   colorNameLabel.font = [UIFont boldSystemFontOfSize:24];

                   colorNameLabel.text = keyForTheColor;

                   [returnView addSubview:colorView];
                   [returnView addSubview:colorNameLabel];

                   [colorView release];
                   [colorNameLabel release];
                   [returnView autorelease];
                   return returnView;

               }

               - (void) pickerView: (UIPickerView *) pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
               {
                   NSString *keyForTheColor = [[self.colorDictionary allKeys] objectAtIndex:row];
                   UIColor *selectedColor = [self.colorDictionary valueForKey:keyForTheColor];

                   aCanvasView.strokeColor = selectedColor;
               }
Shake
     Shake
     shake      Motion event
layer            path              - cgContext           0.7
             setNeedsDisplay                 - layer            path
                                                             (cgContext)
                                             -layer
                                             - setNeedsDisplay




                                  drawRect

                -                            (context)
                -                            (context)


                                                                           .

Más contenido relacionado

La actualidad más candente

Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Marakana Inc.
 
Understanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersUnderstanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersAriya Hidayat
 
SIGGRAPH Asia 2012 Exhibitor Talk: OpenGL 4.3 and Beyond
SIGGRAPH Asia 2012 Exhibitor Talk: OpenGL 4.3 and BeyondSIGGRAPH Asia 2012 Exhibitor Talk: OpenGL 4.3 and Beyond
SIGGRAPH Asia 2012 Exhibitor Talk: OpenGL 4.3 and BeyondMark Kilgard
 
SIGGRAPH 2012: NVIDIA OpenGL for 2012
SIGGRAPH 2012: NVIDIA OpenGL for 2012SIGGRAPH 2012: NVIDIA OpenGL for 2012
SIGGRAPH 2012: NVIDIA OpenGL for 2012Mark Kilgard
 
Android graphics
Android graphicsAndroid graphics
Android graphicsKrazy Koder
 
GTC 2012: GPU-Accelerated Path Rendering
GTC 2012: GPU-Accelerated Path RenderingGTC 2012: GPU-Accelerated Path Rendering
GTC 2012: GPU-Accelerated Path Rendering Mark Kilgard
 
Google I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics PerformanceGoogle I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics PerformanceDouO
 
Graphics on the Go
Graphics on the GoGraphics on the Go
Graphics on the GoGil Irizarry
 
Cloud computing benefits start-up companies
Cloud computing benefits start-up companiesCloud computing benefits start-up companies
Cloud computing benefits start-up companiesSang-il Jung
 
SIGGRAPH 2012: GPU-Accelerated 2D and Web Rendering
SIGGRAPH 2012: GPU-Accelerated 2D and Web RenderingSIGGRAPH 2012: GPU-Accelerated 2D and Web Rendering
SIGGRAPH 2012: GPU-Accelerated 2D and Web RenderingMark Kilgard
 
Performant, accessible animations with CSS & a dash of JavaScript
Performant, accessible animations with CSS & a dash of JavaScriptPerformant, accessible animations with CSS & a dash of JavaScript
Performant, accessible animations with CSS & a dash of JavaScriptsoyarsauce
 
GTC 2012: NVIDIA OpenGL in 2012
GTC 2012: NVIDIA OpenGL in 2012GTC 2012: NVIDIA OpenGL in 2012
GTC 2012: NVIDIA OpenGL in 2012Mark Kilgard
 

La actualidad más candente (12)

Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)
 
Understanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersUnderstanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile Browsers
 
SIGGRAPH Asia 2012 Exhibitor Talk: OpenGL 4.3 and Beyond
SIGGRAPH Asia 2012 Exhibitor Talk: OpenGL 4.3 and BeyondSIGGRAPH Asia 2012 Exhibitor Talk: OpenGL 4.3 and Beyond
SIGGRAPH Asia 2012 Exhibitor Talk: OpenGL 4.3 and Beyond
 
SIGGRAPH 2012: NVIDIA OpenGL for 2012
SIGGRAPH 2012: NVIDIA OpenGL for 2012SIGGRAPH 2012: NVIDIA OpenGL for 2012
SIGGRAPH 2012: NVIDIA OpenGL for 2012
 
Android graphics
Android graphicsAndroid graphics
Android graphics
 
GTC 2012: GPU-Accelerated Path Rendering
GTC 2012: GPU-Accelerated Path RenderingGTC 2012: GPU-Accelerated Path Rendering
GTC 2012: GPU-Accelerated Path Rendering
 
Google I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics PerformanceGoogle I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics Performance
 
Graphics on the Go
Graphics on the GoGraphics on the Go
Graphics on the Go
 
Cloud computing benefits start-up companies
Cloud computing benefits start-up companiesCloud computing benefits start-up companies
Cloud computing benefits start-up companies
 
SIGGRAPH 2012: GPU-Accelerated 2D and Web Rendering
SIGGRAPH 2012: GPU-Accelerated 2D and Web RenderingSIGGRAPH 2012: GPU-Accelerated 2D and Web Rendering
SIGGRAPH 2012: GPU-Accelerated 2D and Web Rendering
 
Performant, accessible animations with CSS & a dash of JavaScript
Performant, accessible animations with CSS & a dash of JavaScriptPerformant, accessible animations with CSS & a dash of JavaScript
Performant, accessible animations with CSS & a dash of JavaScript
 
GTC 2012: NVIDIA OpenGL in 2012
GTC 2012: NVIDIA OpenGL in 2012GTC 2012: NVIDIA OpenGL in 2012
GTC 2012: NVIDIA OpenGL in 2012
 

Similar a 아이폰강의(7) pdf

Total Knockout: Start-to-Finish Development of Suitability Applications Using...
Total Knockout: Start-to-Finish Development of Suitability Applications Using...Total Knockout: Start-to-Finish Development of Suitability Applications Using...
Total Knockout: Start-to-Finish Development of Suitability Applications Using...Blue Raster
 
Basic of computer graphic - Computer Graphic - Notes
Basic of computer graphic - Computer Graphic - NotesBasic of computer graphic - Computer Graphic - Notes
Basic of computer graphic - Computer Graphic - NotesOmprakash Chauhan
 
Digital Dynamic Markers in augmented Reality
Digital Dynamic Markers in augmented RealityDigital Dynamic Markers in augmented Reality
Digital Dynamic Markers in augmented RealityAyan Sinha
 
Unit 3-ASSEMBLY OF PARTS AND CAD STANDARDS.pptx
Unit 3-ASSEMBLY OF PARTS AND CAD STANDARDS.pptxUnit 3-ASSEMBLY OF PARTS AND CAD STANDARDS.pptx
Unit 3-ASSEMBLY OF PARTS AND CAD STANDARDS.pptxdinesh babu
 
Raster Editing & Raster to Vector Conversion, Easy with GTX Tools
Raster Editing & Raster to Vector Conversion, Easy with GTX ToolsRaster Editing & Raster to Vector Conversion, Easy with GTX Tools
Raster Editing & Raster to Vector Conversion, Easy with GTX ToolsWindham Document Systems
 
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdf
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdfJIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdf
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdfSamiraKids
 
Talking Technical illustration - Episode 1 - 3D data
Talking Technical illustration - Episode 1 - 3D dataTalking Technical illustration - Episode 1 - 3D data
Talking Technical illustration - Episode 1 - 3D dataLarson Software Technology
 
Introduction to Graphics - Session
Introduction to Graphics - SessionIntroduction to Graphics - Session
Introduction to Graphics - SessionNEEVEE Technologies
 
Designing an Objective-C Framework about 3D
Designing an Objective-C Framework about 3DDesigning an Objective-C Framework about 3D
Designing an Objective-C Framework about 3Drsebbe
 
Converting and Transforming Technical Graphics
Converting and Transforming Technical GraphicsConverting and Transforming Technical Graphics
Converting and Transforming Technical Graphicsdclsocialmedia
 
Computer Graphics Notes
Computer Graphics NotesComputer Graphics Notes
Computer Graphics NotesGurpreet singh
 

Similar a 아이폰강의(7) pdf (20)

Graphics mod
Graphics modGraphics mod
Graphics mod
 
Total Knockout: Start-to-Finish Development of Suitability Applications Using...
Total Knockout: Start-to-Finish Development of Suitability Applications Using...Total Knockout: Start-to-Finish Development of Suitability Applications Using...
Total Knockout: Start-to-Finish Development of Suitability Applications Using...
 
Basic of computer graphic - Computer Graphic - Notes
Basic of computer graphic - Computer Graphic - NotesBasic of computer graphic - Computer Graphic - Notes
Basic of computer graphic - Computer Graphic - Notes
 
(2) gui drawing
(2) gui drawing(2) gui drawing
(2) gui drawing
 
Digital Dynamic Markers in augmented Reality
Digital Dynamic Markers in augmented RealityDigital Dynamic Markers in augmented Reality
Digital Dynamic Markers in augmented Reality
 
CAD STANDARDS
CAD STANDARDSCAD STANDARDS
CAD STANDARDS
 
Webinar - Transforming Graphical Data
Webinar - Transforming Graphical DataWebinar - Transforming Graphical Data
Webinar - Transforming Graphical Data
 
Unit 3-ASSEMBLY OF PARTS AND CAD STANDARDS.pptx
Unit 3-ASSEMBLY OF PARTS AND CAD STANDARDS.pptxUnit 3-ASSEMBLY OF PARTS AND CAD STANDARDS.pptx
Unit 3-ASSEMBLY OF PARTS AND CAD STANDARDS.pptx
 
Raster Editing & Raster to Vector Conversion, Easy with GTX Tools
Raster Editing & Raster to Vector Conversion, Easy with GTX ToolsRaster Editing & Raster to Vector Conversion, Easy with GTX Tools
Raster Editing & Raster to Vector Conversion, Easy with GTX Tools
 
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdf
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdfJIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdf
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdf
 
Hardware Accelerated 2D Rendering for Android
Hardware Accelerated 2D Rendering for AndroidHardware Accelerated 2D Rendering for Android
Hardware Accelerated 2D Rendering for Android
 
What is OpenGL ?
What is OpenGL ?What is OpenGL ?
What is OpenGL ?
 
Talking Technical illustration - Episode 1 - 3D data
Talking Technical illustration - Episode 1 - 3D dataTalking Technical illustration - Episode 1 - 3D data
Talking Technical illustration - Episode 1 - 3D data
 
Introduction to Graphics - Session
Introduction to Graphics - SessionIntroduction to Graphics - Session
Introduction to Graphics - Session
 
Designing an Objective-C Framework about 3D
Designing an Objective-C Framework about 3DDesigning an Objective-C Framework about 3D
Designing an Objective-C Framework about 3D
 
graphics
graphicsgraphics
graphics
 
Converting and Transforming Technical Graphics
Converting and Transforming Technical GraphicsConverting and Transforming Technical Graphics
Converting and Transforming Technical Graphics
 
Computer Graphics Notes
Computer Graphics NotesComputer Graphics Notes
Computer Graphics Notes
 
CAD
CADCAD
CAD
 
VizEx Edit - Technical Illustration Workshop
VizEx Edit - Technical Illustration WorkshopVizEx Edit - Technical Illustration Workshop
VizEx Edit - Technical Illustration Workshop
 

Más de sunwooindia

아이폰강의(6) pdf
아이폰강의(6) pdf아이폰강의(6) pdf
아이폰강의(6) pdfsunwooindia
 
2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서sunwooindia
 
2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서sunwooindia
 
2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서sunwooindia
 
아이폰강의(5) pdf
아이폰강의(5) pdf아이폰강의(5) pdf
아이폰강의(5) pdfsunwooindia
 
아이폰강의(4) pdf
아이폰강의(4) pdf아이폰강의(4) pdf
아이폰강의(4) pdfsunwooindia
 
아이폰강의(3)
아이폰강의(3)아이폰강의(3)
아이폰강의(3)sunwooindia
 
아이폰프로그래밍(2)
아이폰프로그래밍(2)아이폰프로그래밍(2)
아이폰프로그래밍(2)sunwooindia
 
오브젝트C(pdf)
오브젝트C(pdf)오브젝트C(pdf)
오브젝트C(pdf)sunwooindia
 

Más de sunwooindia (9)

아이폰강의(6) pdf
아이폰강의(6) pdf아이폰강의(6) pdf
아이폰강의(6) pdf
 
2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서
 
2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서
 
2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서2011년 상반기 스마트폰이용실태조사 요약보고서
2011년 상반기 스마트폰이용실태조사 요약보고서
 
아이폰강의(5) pdf
아이폰강의(5) pdf아이폰강의(5) pdf
아이폰강의(5) pdf
 
아이폰강의(4) pdf
아이폰강의(4) pdf아이폰강의(4) pdf
아이폰강의(4) pdf
 
아이폰강의(3)
아이폰강의(3)아이폰강의(3)
아이폰강의(3)
 
아이폰프로그래밍(2)
아이폰프로그래밍(2)아이폰프로그래밍(2)
아이폰프로그래밍(2)
 
오브젝트C(pdf)
오브젝트C(pdf)오브젝트C(pdf)
오브젝트C(pdf)
 

Último

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 

Último (20)

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 

아이폰강의(7) pdf

  • 1. Chapter 9 Core Graphics Bit Academy
  • 2. Quartz Your App Cocoa Touch(UIKit) Core Animation Quartz Core Graphics Graphics Hardware
  • 3. Drawing Quartz and UIKIT • Quartz is the general name for the native window server and drawing technology in iOS. • Core Graphics framework . . • Graphics contexts • Paths • Images and bitmaps • Transparency layers • Colors, pattern colors, and color spaces • Gradients and shadings • Fonts • PDF content
  • 4. Page • Quartz painter model . • page . • page .
  • 5. Graphics Context • Graphics Context • • ( , ) • User Space Device Space .
  • 6. Graphics Context Graphics Context Your App Cocoa Touch(UIKit) Quartz Core Animation Core Graphics Graphics Hardware
  • 7. Graphics Context Graphics Context . • A bitmap graphics context allows you to paint RGB colors, CMYK colors, or grayscale into a bitmap. A bitmap is a rectangular array (or raster) of pixels, each pixel representing a point in an image. Bitmap images are also called sampled images. See “Creating a Bitmap Graphics Context.” • A PDF graphics context allows you to create a PDF file. In a PDF file, your drawing is preserved as a sequence of commands. There are some significant differences between PDF files and bitmaps: 1 PDF files, unlike bitmaps, may contain more than one page. 2 When you draw a page from a PDF file on a different device, the resulting image is optimized for the display characteristics of that device. 3 PDF files are resolution independent by nature—the size at which they are drawn can be increased or decreased infinitely without sacrificing image detail. The user-perceived quality of a bitmap image is tied to the resolution at which the bitmap is intended to be viewed. • See “Creating a PDF Graphics Context.” • A window graphics context is a graphics context that you can use to draw into a window. Note that because Quartz 2D is a graphics engine and not a window management system, you use one of the application frameworks to obtain a graphics context for a window. See “Creating a Window Graphics Context in Mac OS X” for details. • A layer context (CGLayerRef) is an offscreen drawing destination associated with another graphics context. It is designed for optimal performance when drawing the layer to the graphics context that created it. A layer context can be a much better choice for offscreen drawing than a bitmap graphics context. See “Core Graphics Layer Drawing.”
  • 8. Quartz 2D Opaque Data Types Opaque Data Type The opaque data types available in Quartz 2D include the following: • CGPathRef, used for vector graphics to create paths that you fill or stroke. See “Paths.” • CGImageRef, used to represent bitmap images and bitmap image masks based on sample data that you supply. See “Bitmap Images and Image Masks.” • CGLayerRef, used to represent a drawing layer that can be used for repeated drawing (such as for backgrounds or patterns) and for offscreen drawing. See “Core Graphics Layer Drawing” • CGPatternRef, used for repeated drawing. See “Patterns.” • CGShadingRef and CGGradientRef, used to paint gradients. See “Gradients.” • CGFunctionRef, used to define callback functions that take an arbitrary number of floating-point arguments. You use this data type when you create gradients for a shading. See “Gradients.” • CGColorRef and CGColorSpaceRef, used to inform Quartz how to interpret color. See “Color and Color Spaces.” • CGImageSourceRef and CGImageDestinationRef, which you use to move data into and out of Quartz. See “Data Management in Quartz 2D” and Image I/O Programming Guide. • CGFontRef, used to draw text. See “Text.” • CGPDFDictionaryRef, CGPDFObjectRef, CGPDFPageRef, CGPDFStream, CGPDFStringRef, and CGPDFArrayRef, which provide access to PDF metadata. See “PDF Document Creation, Viewing, and Transforming.” • CGPDFScannerRef and CGPDFContentStreamRef, which parse PDF metadata. See “PDF Document Parsing.” • CGPSConverterRef, used to convert PostScript to PDF. It is not available in iOS. See “PostScript Conversion.”
  • 9. Graphics States • Graphics State . • Graphics Context Graphics State . • CGContextSaveGState, CGContextRestoreGState .
  • 10. Graphics States Parameters that are associated with the graphics state •Current transformation matrix (CTM) : “Transforms” •Clipping area :“Paths” •Line: width, join, cap, dash, miter limit : “Paths” •Accuracy of curve estimation (flatness): “Paths” •Anti-aliasing setting: “Graphics Contexts” •Color: fill and stroke settings: “Color and Color Spaces” •Alpha value (transparency): “Color and Color Spaces” •Rendering intent : “Color and Color Spaces” •Color space: fill and stroke settings: “Color and Color Spaces” •Text: font, font size, character spacing, text drawing mode : “Text” •Blend mode : “Paths” and “Bitmap Images and Image Masks”
  • 11. Creating a Bitmap Graphics Context You use the function CGBitmapContextCreate to create a bitmap graphics context. This function takes the following parameters: • data. Supply a pointer to the destination in memory where you want the drawing rendered. The size of this memory block should be at least (bytesPerRow*height) bytes. • width. Specify the width, in pixels, of the bitmap. • height. Specify the height, in pixels, of the bitmap. • bitsPerComponent. Specify the number of bits to use for each component of a pixel in memory. For example, for a 32-bit pixel format and an RGB color space, you would specify a value of 8 bits per component. See “Supported Pixel Formats.” • bytesPerRow. Specify the number of bytes of memory to use per row of the bitmap.Tip:  When you create a bitmap graphics context, you’ll get the best performance if you make sure the data and bytesPerRow are 16-byte aligned. • colorspace. The color space to use for the bitmap context. You can provide a Gray, RGB, CMYK, or NULL color space when you create a bitmap graphics context. For detailed information on color spaces and color management principles, see Color Management Overview. For information on creating and using color spaces in Quartz, see “Color and Color Spaces.” For information about supported color spaces, see “Color Spaces and Bitmap Layout” in the “Bitmap Images and Image Masks” chapter. • bitmapInfo. Bitmap layout information, expressed as a CGBitmapInfo constant, that specifies whether the bitmap should contain an alpha component, the relative location of the alpha component (if there is one) in a pixel, whether the alpha component is premultiplied, and whether the color components are integer or floating-point values.
  • 13. Path path Path , .
  • 14. Path Building Block Points Points are x and y coordinates that specify a location in user space. You can call the function CGContextMoveToPoint to specify a starting position for a new subpath. Lines A line is defined by its endpoints. Its starting point is always assumed to be the current point, so when you create a line, you specify only its endpoint. You use the function CGContextAddLineToPoint to append a single line to a subpath. You can add a series of connected lines to a path by calling the function CGContextAddLines. You pass this function an array of points. The first point must be the starting point of the first line; the remaining points are endpoints. Quartz begins a new subpath at the first point and connects a straight line segment to each endpoint. Arcs Arcs are circle segments. Quartz provides two functions that create arcs. The function CGContextAddArc creates a curved segment from a circle.
  • 15. Path Building Block Curves Figure 3-7  A cubic Bézier curve uses two control points You use the function CGContextAddCurveToPoint to append a cubic Bézier curve from the current point, using control points and an endpoint you specify. Figure 3-8  A quadratic Bézier curve uses one control point You can append a quadratic Bézier curve from the current point by calling the function CGContextAddQuadCurveToPoint, and specifying a control point and an endpoint.
  • 16. Path Building Block Ellipses : CGContextAddEllipseInRect. Rectangles You can add a rectangle to the current path by calling the function CGContextAddRect. You supply a CGRect structure that contains the origin of the rectangle and its width and height.
  • 17. Creating a Path • , CGContextBeginPath . • CGContextMoveToPoint . • When you want to close the current subpath within a path, call the function CGContextClosePath to connect a segment to the starting point of the subpath. Subsequent path calls begin a new subpath, even if you do not explicitly set a new starting point. • When you draw arcs, Quartz draws a line between the current point and the starting point of the arc. • Quartz routines that add ellipses and rectangles add a new closed subpath to the path. • fill stroke . . CGPathRef CGMutablePathRef .
  • 18. Painting a Path You can paint the current path by stroking or filling or both. Stroking paints a line that straddles the path. Filling paints the area contained within the path.
  • 19. Stroke   Parameters that affect how Quartz strokes the current path Functions for Stroking a Path ParameterFunction to set parameter value Quartz provides the functions for stroking the current path. Some Line width are convenience functions for stroking rectangles or ellipses. CGContextSetLineWidth Functions that stroke paths Line join Function CGContextSetLineJoin CGContextStrokePath Line cap Strokes the current path. CGContextSetLineCap CGContextStrokeRect Miter limit Strokes the specified rectangle. CGContextSetMiterLimit CGContextStrokeRectWithWidth Line dash pattern Strokes the specified rectangle, using the specified line width. CGContextSetLineDash CGContextStrokeEllipseInRect Stroke color space Strokes an ellipse that fits inside the specified rectangle. CGContextSetStrokeColorSpace CGContextStrokeLineSegments: Stroke color Strokes a sequence of lines. CGContextSetStrokeColorCGContextSetStrokeColorWithColor CGContextDrawPath : Stroke pattern If you pass the constant kCGPathStroke, strokes the current CGContextSetStrokePattern path. See “Filling a Path” if you want to both fill and stroke a path.
  • 20. Fill  Functions that fill paths Function Description CGContextEOFillPath Fills the current path using the even-odd rule. CGContextFillPath Fills the current path using the nonzero winding number rule. CGContextFillRect Fills the area that fits inside the specified rectangle. CGContextFillRects Fills the areas that fits inside the specified rectangles. CGContextFillEllipseInRect Fills an ellipse that fits inside the specified rectangle. CGContextDrawPath Fills the current path if you pass kCGPathFill (nonzero winding number rule) or kCGPathEOFill (even-odd rule). Fills and strokes the current path if you pass kCGPathFillStroke or kCGPathEOFillStroke.
  • 21. Color and Color Spaces User Space device color . Color : color space Color Space: Table 4-1  Color values in different color spaces Values value color space components 240 degrees, Hue, saturation, 100%, 100% HSB brightness 0, 0, 1 RGB Red, green, blue 1, 1, 0, 0 Cyan, magenta, CMYK yellow, black 1, 0, 0 BGR Blue, green, red
  • 23. Creating Device Color Spaces Device color spaces are primarily used by iOS applications because other options are not available. In most cases, a Mac OS X application should use a generic color space instead of creating a device color space. However, some Quartz routines expect images with a device color space. For example, if you call CGImageCreateWithMask and specify an image as the mask, the image must be defined with the device gray color space. You create a device color space by using one of the following functions: • CGColorSpaceCreateDeviceGray for a device-dependent grayscale color space. • CGColorSpaceCreateDeviceRGB for a device-dependent RGB color space. • CGColorSpaceCreateDeviceCMYK for a device-dependent CMYK color space.
  • 24. About Quartz Transformation Functions User Space translate( ), rotate( ), scale( , ) . Graphic Context 3 CTM(Current Transformation Matrix) identity matrix .
  • 25. Transformation CGContextTranslateCTM (myContext, w/4, 0); CGContextScaleCTM (myContext, .25, .5); CGContextRotateCTM (myContext, radians ( 22.));
  • 26. Creating Affine Transforms The affine transform functions available in Quartz operate on matrices, not on the CTM. You can use these functions to construct a matrix that you later apply to the CTM by calling the function CGContextConcatCTM. Affine transform functions for translation, rotation, and scaling Functio CGAffineTransformMakeTranslation To construct a new translation matrix from x and y values that specify how much to move the origin. CGAffineTransformTranslate To apply a translation operation to an existing affine transform. CGAffineTransformMakeRotation To construct a new rotation matrix from a value that specifies in radians how much to rotate the coordinate system. CGAffineTransformRotate To apply a rotation operation to an existing affine transform. CGAffineTransformMakeScale To construct a new scaling matrix from x and y values that specify how much to stretch or shrink coordinates. CGAffineTransformScale To apply a scaling operation to an existing affine transform.
  • 27.
  • 28. C API ✴ Create CGContextRelese(Context) . ✴ Get . • ✴ : ✴ : . • ✴ , CGColorSpaceCreateDeviceRGB • ✴ Affine Transform / , , , .
  • 29. UIResponder Class Managing the Responder Chain 1 – nextResponder 2 – isFirstResponder motionBegan:withEvent: 3 – canBecomeFirstResponder Tells the receiver that a motion event has begun. 4 – becomeFirstResponder - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event 5 – canResignFirstResponder 6 – resignFirstResponder Parameters motion Managing Input Views An event-subtype constant indicating the kind of motion. A common motion is shaking, 1   inputView  property which is indicated by UIEventSubtypeMotionShake. 2   inputAccessoryView  property event 3 – reloadInputViews An object representing the event associated with the motion. Responding to Touch Events Discussion 1 – touchesBegan:withEvent: iOS informs the first responder only when a motion event starts and when it ends; for 2 – touchesMoved:withEvent: example, it doesn’t report individual shakes. The receiving object must be the first 3 – touchesEnded:withEvent: responder to receive motion events. 4 – touchesCancelled:withEvent: Responding to Motion Events The default implementation of this method does nothing. However immediate UIKit subclasses of UIResponder, particularly UIView, forward the message up the responder 1 – motionBegan:withEvent: chain. 2 – motionEnded:withEvent: 3 – motionCancelled:withEvent: Responding to Remote-Control Events 1 – remoteControlReceivedWithEvent: Getting the Undo Manager 1   undoManager  property Validating Commands 1 – canPerformAction:withSender:
  • 30. UITouch Class gestureRecognizers The gesture recognizers that are receiving the touch object. Getting the Location of Touches @property(nonatomic,readonly,copy) NSArray *gestureRecognizers 1 – locationInView: Discussion 2 – previousLocationInView: The objects in the array are instances of a subclass of the abstract base class 3   view  property UIGestureRecognizer. If there are no gesture recognizers currently receiving the touch 4   window  property objects, this property holds an empty array. Getting Touch Attributes 1   tapCount  property 2   timestamp  property 3   phase  property Getting a Touch Object’s Gesture Recognizers 1   gestureRecognizers  property previousLocationInView: Returns the previous location of the receiver in the coordinate system of the given view. - (CGPoint)previousLocationInView:(UIView *)view locationInView: Returns the current location of the receiver in the coordinate system of the given view. - (CGPoint)locationInView:(UIView *)view
  • 31. UIEvent UIEvent Class subtype Returns the subtype of the event. (read-only) - @property(readonly) UIEventSubtype subtype - Discussion The UIEventSubtype constant returned by this property indicates the - : / , subtype of the event in relation to the general type, which is returned from the type property. Responder . typedef enum { UIEventSubtypeNone = 0, , , , UIEventSubtypeMotionShake = 1, . UIEventSubtypeRemoteControlPlay = 100, UIEventSubtypeRemoteControlPause = 101, shake remote- UIEventSubtypeRemoteControlStop = 102, control play, previous track . UIEventSubtypeRemoteControlTogglePlayPause = 103, motionBegan:withEvent: , remoteControlReceivedWithEvent: UIEventSubtypeRemoteControlNextTrack = 104, UIEventSubtypeRemoteControlPreviousTrack = 105, UIEventSubtypeRemoteControlBeginSeekingBackward = 106, UIEventSubtypeRemoteControlEndSeekingBackward = 107, Getting the Touches for an Event UIEventSubtypeRemoteControlBeginSeekingForward = 108, 1 – allTouches UIEventSubtypeRemoteControlEndSeekingForward = 109, 2 – touchesForView: } UIEventSubtype; 3 – touchesForWindow: Getting Event Attributes type 1   timestamp  property Returns the type of the event. (read-only) Getting the Event Type @property(readonly) UIEventType type 1   type  property 2   subtype  property typedef enum { Getting the Touches for a Gesture Recognizer UIEventTypeTouches, 1 – touchesForGestureRecognizer: UIEventTypeMotion, UIEventTypeRemoteControl, allTouches } UIEventType; Returns all touch objects associated with the receiver. - (NSSet *)allTouches Return Value A set of UITouch objects representing all touches associated with an event (represented by the receiver). Discussion If the touches of the event originate in different views and windows, the UITouch objects obtained from this
  • 32. CGColor CGColorGetComponents Returns the values of the color components (including alpha) associated with a Quartz color. const CGFloat * CGColorGetComponents ( CGColorRef color ); Parameters color A Quartz color. Return Value An array of intensity values for the color components (including alpha) associated with the specified color. The size of the array is one more than the number of components of the color space for the color.
  • 33. UIColor Tasks Creating a UIColor Object from Component Values 1 + colorWithWhite:alpha: CGColor 2 + colorWithHue:saturation:brightness:alpha: The Quartz color reference that corresponds to the receiver’s color. (read-o 3 + colorWithRed:green:blue:alpha: 4 + colorWithCGColor: @property(nonatomic,readonly) CGColorRef CGColor 5 + colorWithPatternImage: 6 – colorWithAlphaComponent: Initializing a UIColor Object 1 – initWithWhite:alpha: 2 – initWithHue:saturation:brightness:alpha: System Colors 3 – initWithRed:green:blue:alpha: 1 + lightTextColor 4 – initWithCGColor: 2 + darkTextColor 5 – initWithPatternImage: 3 + groupTableViewBackgroundColor Creating a UIColor with Preset Component Values 4 + viewFlipsideBackgroundColor 1 + blackColor 5 + scrollViewTexturedBackgroundColor 2 + darkGrayColor Retrieving Color Information 3 + lightGrayColor 1   CGColor  property 4 + whiteColor 5 + grayColor Drawing Operations 6 + redColor 1 – set 7 + greenColor 2 – setFill 8 + blueColor 3 – setStroke 9 + cyanColor 10 + yellowColor 11 + magentaColor 12 + orangeColor 13 + purpleColor 14 + brownColor 15 + clearColor
  • 34. View Animation beginAnimations:context: Marks the beginning of a begin/commit animation block. + (void)beginAnimations:(NSString *)animationID context:(void *)context Parameters animationID An application-supplied identifier for the animations. context Custom data that you want to associate with this set of animations. information that is passed to the animation delegate messages—the selectors set using the setAnimationWillStartSelector: and setAnimationDidStopSelector: methods. Discussion Use of this method is discouraged in iOS 4.0 and later. You should use the block-based animation methods to specify your animations instead. This method signals to the system that you want to specify the beginning of an animation block. After calling this method, your application should configure the animation options (using the setAnimation class methods) and then change the desired animatable properties of your views. When you are done changing your view properties, call the commitAnimations method to close the set and schedule the animations. You can nest sets of animations (by calling this method again before committing a previous set of animations) as needed. Nesting animations groups them together and allows you to set different animation options for the nested group. If you install a start or stop selector using the setAnimationWillStartSelector: or setAnimationDidStopSelector: method, the values you specify for the animationID and context parameters are passed to your selectors at runtime. You can use these parameters to pass additional information to those selectors.
  • 35. View Animation setAnimationTransition:forView:cache: Sets a transition to apply to a view during an animation block. + (void)setAnimationTransition:(UIViewAnimationTransition)transition forView:(UIView *)view cache:(BOOL)cache Parameters transition A transition to apply to view. Possible values are described in UIViewAnimationTransition. view The view to apply the transition to. cache If YES, the before and after images of view are rendered once and used to create the frames in the animation. Caching can improve performance but if you set this parameter to YES, you must not update the view or its subviews during the transition. Updating the view and its subviews may interfere with the caching behaviors and cause the view contents to be rendered incorrectly (or in the wrong location) during the animation. You must wait until the transition ends to update the view. If NO, the view and its contents must be updated for each frame of the transition animation, which may noticeably affect the frame rate. Discussion Use of this method is discouraged in iOS 4.0 and later. You should use the transitionWithView:duration:options:animations:completion: method to perform transitions instead. If you want to change the appearance of a view during a transition—for example, flip from one view to another—then use a container view, an instance of UIView, as follows: 1. Begin an animation block. 2. Set the transition on the container view. 3. Remove the subview from the container view. 4. Add the new subview to the container view. 5. Commit the animation block.
  • 36. View Animation commitAnimations Marks the end of a begin/commit animation block and schedules the animations for execution. + (void)commitAnimations Discussion Use of this method is discouraged in iOS 4.0 and later. You should use the block-based animation methods to specify your animations instead. If the current animation set is the outermost set, this method starts the animations when the application returns to the run loop. If the current animation set is nested inside another set, this method waits until the outermost set of animations is committed, at which point it commits all of the animations together. Animations run in a separate thread to avoid blocking the application. In this way, multiple animations can be piled on top of one another. See setAnimationBeginsFromCurrentState: for how to start animations while others are in progress.
  • 37. PickerView Class Tasks Getting the Dimensions of the View Picker 1   numberOfComponents  property 2 – numberOfRowsInComponent: 3 – rowSizeForComponent: Reloading the View Picker 1 – reloadAllComponents 2 – reloadComponent: Selecting Rows in the View Picker 1 – selectRow:inComponent:animated: 2 – selectedRowInComponent: Returning the View for a Row and Component 1 – viewForRow:forComponent: Specifying the Delegate 1   delegate  property Specifying the Data Source 1   dataSource  property Managing the Appearance of the Picker View 1   showsSelectionIndicator  property
  • 38. PickerView DataSource Protocol Tasks Providing Counts for the Picker View 1 – numberOfComponentsInPickerView: 2 – pickerView:numberOfRowsInComponent: numberOfComponentsInPickerView: Called by the picker view when it needs the number of components. (required) - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView Parameters pickerView The picker view requesting the data. Return Value The number of components (or “columns”) that the picker view should display. pickerView:numberOfRowsInComponent: Called by the picker view when it needs the number of rows for a specified component. (required) - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component Parameters pickerView The picker view requesting the data. component A zero-indexed number identifying a component of pickerView. Components are numbered left-to-right.
  • 39. PickerView Delegate Protocol Setting the Dimensions of the Picker View 1 – pickerView:rowHeightForComponent: pickerView:titleForRow:forComponent: 2 – pickerView:widthForComponent: Called by the picker view when it needs the title to use Setting the Content of Component Rows for a given row in a given component. The methods in this group are marked @optional. However, to use a picker view, you - (NSString *)pickerView:(UIPickerView *) must implement either the pickerView:titleForRow:forComponent: or the pickerView titleForRow:(NSInteger)row pickerView:viewForRow:forComponent:reusingView: method to provide the content forComponent:(NSInteger)component of component rows. Parameters pickerView 1 – pickerView:titleForRow:forComponent: An object representing the picker view requesting the 2 – pickerView:viewForRow:forComponent:reusingView: data. Responding to Row Selection row 1 – pickerView:didSelectRow:inComponent: A zero-indexed number identifying a row of component. Rows are numbered top-to-bottom. pickerView:viewForRow:forComponent:reusingView: component Called by the picker view when it needs the view to use for a given row in a given A zero-indexed number identifying a component of component. pickerView. Components are numbered left-to-right. Return Value - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger) The string to use as the title of the indicated component row forComponent:(NSInteger)component reusingView:(UIView *)view row. Parameters pickerView An object representing the picker view requesting the data. row A zero-indexed number identifying a row of component. Rows are numbered top-to- bottom. component A zero-indexed number identifying a component of pickerView. Components are numbered left-to-right. view A view object that was previously used for this row, but is now hidden and cached by the picker view. Return Value A view object to use as the content of row. The object can be any subclass of UIView, such as UILabel, UIImageView, or even a custom view.
  • 40. NSDictionary Class initWithObjects:forKeys: Initializes a newly allocated dictionary with entries constructed from the contents of the objects and keys arrays. - (id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys Parameters objects An array containing the values for the new dictionary. keys An array containing the keys for the new dictionary. Each key is copied (using copyWithZone:; keys must conform to the NSCopying protocol), and the copy is added to the new dictionary. Discussion This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. An NSInvalidArgumentException is raised if the objects and keys arrays do not have the same number of elements. allKeys Returns a new array containing the dictionary’s keys. - (NSArray *)allKeys Return Value A new array containing the dictionary’s keys, or an empty array if the dictionary has no entries. Discussion The order of the elements in the array is not defined.
  • 41. UIAlertView Class initWithTitle:message:delegate:cancelButtonTitle:otherButton Titles: Convenience method for initializing an alert view. - (id)initWithTitle:(NSString *)title message:(NSString *)message delegate: (id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... Parameters title The string that appears in the receiver’s title bar. message Descriptive text that provides more details than the title. show Displays the receiver using animation. delegate The receiver’s delegate or nil if it doesn’t have a delegate. - (void)show cancelButtonTitle The title of the cancel button or nil if there is no cancel button. Using this argument is equivalent to setting the cancel button index to the value returned by invoking addButtonWithTitle: specifying this title. otherButtonTitles, The title of another button. Using this argument is equivalent to invoking addButtonWithTitle: with this title to add more buttons. ... Titles of additional buttons to add to the receiver, terminated with nil. Return Value Newly initialized alert view.
  • 42. UIAlertViewDelegate Protocol Reference alertView:clickedButtonAtIndex: Sent to the delegate when the user clicks a button on an alert view. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex: (NSInteger)buttonIndex Parameters alertView The alert view containing the button. buttonIndex The position of the clicked button. The button indices start at 0. Discussion The receiver is automatically dismissed after this method is invoked.
  • 43.
  • 44. #import "SimpleSketchAppDelegate.h" #import "CanvasView.h" @implementation SimpleSketchAppDelegate @synthesize window=_window; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *) launchOptions { // Override point for customization after application launch. CanvasView *aCanvasView = [[CanvasView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; aCanvasView.backgroundColor = [UIColor darkGrayColor]; [self.window addSubview:aCanvasView]; [self.window makeKeyAndVisible]; return YES; }
  • 45. CanvasView.m - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); cgContext = CGBitmapContextCreate(NULL, frame.size.width, frame.size.height, 8, 4*frame.size.width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextSetLineWidth(cgContext, 25); CGContextSetLineCap(cgContext, kCGLineCapRound); CGContextSetRGBStrokeColor(cgContext, 1.0, 1.0, 1.0, 1.0); } return self; } CanvasView.h @interface CanvasView : UIView { CGContextRef cgContext; } @end
  • 46. CGColorSpaceCreateDeviceRGB Creates a device-dependent RGB color space. CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void); Return Value A device-dependent RGB color space. You are responsible for releasing this object by calling CGColorSpaceRelease. If unsuccessful, returns NULL. CGBitmapContextCreate Creates a bitmap graphics context. CGContextRef CGBitmapContextCreate ( void *data, size_t width, size_t height, size_t bitsPerComponent, size_t bytesPerRow, CGColorSpaceRef colorspace, CGBitmapInfo bitmapInfo ); Parameters data A pointer to the destination in memory where the drawing is to be rendered. The size of this memory block should be at least (bytesPerRow*height) bytes. You can pass NULL if you want Quartz to allocate memory for the bitmap. This frees you from managing your own memory, which reduces memory leak issues. width : The width, in pixels, of the required bitmap. height : The height, in pixels, of the required bitmap. bitsPerComponent : The number of bits to use for each component of a pixel in memory. For example, for a 32-bit pixel format and an RGB color space, you would specify a value of 8 bits per component. For the list of supported pixel formats, see “Supported Pixel Formats” in the “Graphics Contexts” chapter of Quartz 2D Programming Guide. bytesPerRow : The number of bytes of memory to use per row of the bitmap. colorspace : The color space to use for the bitmap context. Note that indexed color spaces are not supported for bitmap graphics contexts. bitmapInfo Constants that specify whether the bitmap should contain an alpha channel, the alpha channel’s relative location in a pixel, and information about whether the pixel components are floating-point or integer values. The constants for specifying the alpha channel information are declared with the CGImageAlphaInfo type but can be passed to this parameter safely. You can also pass the other constants associated with the CGBitmapInfo type. (See CGImage Reference for a description of the CGBitmapInfo and CGImageAlphaInfo constants.) For an example of how to specify the color space, bits per pixel, bits per pixel component, and bitmap information using the CGBitmapContextCreate function, see “Creating a Bitmap Graphics Context” in the “Graphics Contexts” chapter of Quartz 2D Programming Guide. Return Value A new bitmap context, or NULL if a context could not be created. You are responsible for releasing this object using CGContextRelease.
  • 47. initWithFrame: Initializes and returns a newly allocated view object with the specified frame rectangle. View - (id)initWithFrame:(CGRect)aRect Parameters aRect The frame rectangle for the view, measured in points. The origin of the frame is relative to the superview in which you plan to add it. This method uses the frame rectangle to set . the center and bounds properties accordingly. Return Value An initialized view object or nil if the object couldn't be created. Discussion The new view object must be inserted into the view hierarchy of a window before it can be used. If you create a view object programmatically, this method is the designated initializer for the UIView class. Subclasses can override this method to perform any custom initialization but must call super at the beginning of their implementation. If you use Interface Builder to design your interface, this method is not called when your view objects are subsequently loaded from the nib file. Objects in a nib file are reconstituted and then initialized using their initWithCoder: method, which modifies the attributes of the view to match the attributes stored in the nib file. For detailed information about how views are loaded from a nib file, see Resource Programming Guide.
  • 48. UIView Class UIResponder Class UIResponder . -(void)touchesBegan:(NSSet *) touches withEvent:(UIEvent *)event -(void)touchesMoved:(NSSet *) touches withEvent:(UIEvent *)event -(void)touchesEnded:(NSSet *) touches withEvent:(UIEvent *)event touchesBegan: touchesMoved . touchesEnded: .
  • 49. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch; for (touch in touches) { CGPoint location = [touch locationInView:self]; CGPoint preLocation = [touch previousLocationInView:self]; NSLog(@"PrevLoc = %@, Loc = %@", NSStringFromCGPoint(preLocation), NSStringFromCGPoint(location)); cgContext CGContextBeginPath(cgContext); preLocation CGContextMoveToPoint(cgContext, preLocation.x, preLocation.y); CGContextAddLineToPoint(cgContext, location.x, location.y); CGContextStrokePath(cgContext); Location } [self setNeedsDisplay]; } CanvasView -drawRect:
  • 50. - (void)drawRect:(CGRect)rect UIGraphicsGetCurrentContext { Returns the current graphics context. // Drawing code CGRect bounds = [self bounds]; CGContextRef UIGraphicsGetCurrentContext ( CGContextRef context = UIGraphicsGetCurrentContext(); void CGImageRef image = CGBitmapContextCreateImage(cgContext); ); CGContextDrawImage(context, bounds, image); Return Value CGImageRelease(image); The current graphics context. } Discussion The current graphics context is nil by default. Prior to calling its drawRect: method, view objects push a valid context onto the stack, making it current. If CGContextDrawImage you are not using a UIView object to do your drawing, however, you must push a Draws an image into a graphics context. valid context onto the stack manually using the UIGraphicsPushContext function. void CGContextDrawImage ( CGContextRef c, You should call this function from the main thread of your application only. CGRect rect, CGImageRef image ); CGBitmapContextCreateImage Parameters Creates and returns a Quartz image from the pixel data in a bitmap graphics context. c CGImageRef CGBitmapContextCreateImage ( The graphics context in which to draw the image. CGContextRef c rect ); The location and dimensions in user space of the Parameters bounding box in which to draw the image. c image A bitmap graphics context. The image to draw. Return Value Discussion A CGImage object that contains a snapshot of the bitmap graphics context or NULL if the image Quartz scales the image—disproportionately, if is not created. necessary—to fit the bounds specified by the rect Discussion parameter. The CGImage object returned by this function is created by a copy operation. Subsequent changes to the bitmap graphics context do not affect the contents of the returned image. In some cases the copy operation actually follows copy-on-write semantics, so that the actual physical copy of the bits occur only if the underlying data in the bitmap graphics context is modified. As a consequence, you may want to use the resulting image and release it before you perform additional drawing into the bitmap graphics context. In this way, you can avoid the actual physical copy of the data.
  • 51. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions { // Override point for customization after application launch. CanvasView *aCanvasView = [[CanvasView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; aCanvasView.backgroundColor = [UIColor darkGrayColor]; aCanvasView.multipleTouchEnabled = YES; [self.window addSubview:aCanvasView]; [self.window makeKeyAndVisible]; return YES; } .
  • 52. ( ) • CGLayer ( ),
  • 53. @interface CanvasView : UIView { CGLayer CGContextRef cgContext; CGLayerRef cgLayer; } @end - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); cgContext = CGBitmapContextCreate(NULL, frame.size.width, frame.size.height, 8, 4*frame.size.width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); cgLayer = CGLayerCreateWithContext(cgContext, frame.size, NULL); CGContextRef context = CGLayerGetContext(cgLayer); CGContextSetLineWidth(context, 25); CGContextSetLineCap(context, kCGLineCapRound); CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); } return self; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event - (void)drawRect:(CGRect)rect { { UITouch *touch; // Drawing code CGRect bounds = [self bounds]; for (touch in touches) { CGContextRef context = UIGraphicsGetCurrentContext(); CGPoint location = [touch locationInView:self]; CGPoint preLocation = [touch previousLocationInView:self]; CGImageRef image = CGBitmapContextCreateImage(cgContext); NSLog(@"PrevLoc = %@, Loc = %@", NSStringFromCGPoint(preLocation), CGContextDrawImage(context, bounds, image); NSStringFromCGPoint(location)); CGImageRelease(image); CGContextRef context = CGLayerGetContext(cgLayer); CGContextSetAlpha(context, 0.7); CGContextBeginPath(context); CGContextDrawLayerInRect(context, bounds, cgLayer); CGContextMoveToPoint(context, preLocation.x, preLocation.y); } CGContextAddLineToPoint(context, location.x, location.y); CGContextStrokePath(context); } [self setNeedsDisplay]; } - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 0.7 CGRect bounds = [self bounds]; CGContextSetAlpha(cgContext, 0.7); CGContextDrawLayerInRect(cgContext, bounds, cgLayer); CGContextClearRect(CGLayerGetContext(cgLayer), bounds); [self setNeedsDisplay]; }
  • 54. CGContextDrawLayerInRect Draws the contents of a CGLayer object into the specified rectangle. void CGContextDrawLayerInRect ( CGContextRef context, CGRect rect, CGLayerRef layer ); Parameters context The graphics context associated with the layer. rect The rectangle, in current user space coordinates, to draw to. layer The layer whose contents you want to draw. Discussion The contents are scaled, if necessary, to fit into the rectangle. CGContextSetAlpha Sets the opacity level for objects drawn in a graphics context. void CGContextSetAlpha ( CGContextRef c, CGFloat alpha ); Parameters c The graphics context for which to set the current graphics state’s alpha value parameter. alpha A value that specifies the opacity level. Values can range from 0.0 (transparent) to 1.0 (opaque). Values outside this range are clipped to 0.0 or 1.0. Discussion This function sets the alpha value parameter for the specified graphics context. To clear the contents of the drawing canvas, use CGContextClearRect.
  • 55. CGLayerCreateWithContext Creates a CGLayer object that is associated with a graphics context. CGLayerRef CGLayerCreateWithContext ( CGContextRef context, CGSize size, CFDictionaryRef auxiliaryInfo ); Parameters context The graphics context you want to create the layer relative to. The layer uses this graphics context as a reference for initialization. size The size, in default user space units, of the layer relative to the CGContextClearRect Paints a transparent rectangle. graphics context. auxiliaryInfo void CGContextClearRect ( Reserved for future use. Pass NULL. CGContextRef c, CGRect rect Return Value ); A CGLayer object. You are responsible for releasing this object Parameters using the function CGLayerRelease when you no longer need the c layer. The graphics context in which to paint the rectangle. rect CGLayerGetContext The rectangle, in user space coordinates. Returns the graphics context associated with a CGLayer object. Discussion CGContextRef CGLayerGetContext ( CGLayerRef layer If the provided context is a window ); Parameters or bitmap context, Quartz effectively layer The layer whose graphics context you want to obtain. clears the rectangle. For other context types, Quartz fills the rectangle in a device-dependent manner. However, Return Value you should not use this function in contexts other than window or The graphics context associated with the layer. bitmap contexts. Discussion The context that’s returned is the context for the layer itself, not the context that you specified when you created the layer.
  • 56. Shake UI & KVO KVO UI IB .
  • 57. KVO @interface CanvasView : UIView { CGContextRef cgContext; CGLayerRef cgLayer; int strokeSize; float strokeAlpha; UIColor *strokeColor; } @property int strokeSize; @property float strokeAlpha; @property (retain) UIColor *strokeColor; - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code [self addObserver:self forKeyPath:@"strokeColor" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; [self addObserver:self forKeyPath:@"strokeSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); cgContext = CGBitmapContextCreate(NULL, frame.size.width, frame.size.height, 8, 4*frame.size.width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); cgLayer = CGLayerCreateWithContext(cgContext, frame.size, NULL); CGContextRef context = CGLayerGetContext(cgLayer); // CGContextSetLineWidth(context, 25); CGContextSetLineCap(context, kCGLineCapRound); // CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); } return self; } - (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"strokeColor"]) { [self updateStrokeColor]; } else if( [keyPath isEqualToString:@"strokeSize"]) { [self updateStrokeSize]; } }
  • 58. @interface CanvasView (Private) -(void) updateStrokeColor; -(void) updateStrokeSize; CanvasView.m @implementation @end - (void) updateStrokeColor { CGContextRef context = CGLayerGetContext(cgLayer); CGFloat *colors = (CGFloat *) CGColorGetComponents(self.strokeColor.CGColor); CGContextSetRGBStrokeColor(context, colors[0], colors[1], colors[2], colors[3]); } - (void) updateStrokeSize { CGContextRef context = CGLayerGetContext(cgLayer); CGContextSetLineWidth(context, self.strokeSize); } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *) launchOptions { // Override point for customization after application launch. CanvasView *aCanvasView = [[CanvasView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; aCanvasView.backgroundColor = [UIColor darkGrayColor]; aCanvasView.multipleTouchEnabled = YES; aCanvasView.strokeSize = 15; aCanvasView.strokeColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1]; aCanvasView.strokeAlpha = 0.7; [self.window addSubview:aCanvasView]; [self.window makeKeyAndVisible]; return YES; }
  • 59. UI (stroke size, alpha, color)
  • 60. #import <UIKit/UIKit.h> @class CanvasView; @interface SimpleSketchAppDelegate : NSObject <UIApplicationDelegate> { CanvasView *aCanvasView; UIView *settingView; UIPickerView *strokeColorPicker; UISlider *strokeSizeSlider; UISlider *strokeAlphaSlider; } -(IBAction) strokeSizeChanged: (id) sender; -(IBAction) strokeAlphaChanged:(id)sender; @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UIView *settingView; @property (nonatomic, retain) IBOutlet UIPickerView *strokeColorPicker; @property (nonatomic, retain) IBOutlet UISlider *strokeSizeSlider; @property (nonatomic, retain) IBOutlet UISlider *strokeAlphaSlider; @implementation SimpleSketchAppDelegate @end @synthesize window=_window; @synthesize settingView; @synthesize strokeSizeSlider; @synthesize strokeAlphaSlider; @synthesize strokeColorPicker; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *) launchOptions { // Override point for customization after application launch. aCanvasView = [[CanvasView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; // aCanvasView.backgroundColor = [UIColor darkGrayColor]; aCanvasView.multipleTouchEnabled = YES; aCanvasView.strokeSize = 15; aCanvasView.strokeColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1]; aCanvasView.strokeAlpha = 0.7; [self.window addSubview:aCanvasView]; [self.window makeKeyAndVisible]; return YES; } -(IBAction) strokeSizeChanged: (id) sender; { } -(IBAction) strokeAlphaChanged:(id)sender
  • 61.
  • 62. PickerView - (NSInteger) numberOfComponentsInPickerView:(UIPickerView *) pickerView . - (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowInComponent:(NSInteger) component . -(NSString *) pickerView: (UIPickerView *)pickerView titleForRow:(NSInteger) row forComponent:(NSInteger) component . -(UIView *) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger) component reusingView:(UIView *)view . -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
  • 63. -(NSDictionary *) colorDictionary { if (colorDictionary != nil) { return colorDictionary; } UIColor *MidNightColor = [UIColor colorWithRed:0 green:0 blue:0.5 alpha:1]; UIColor *TealColor = [UIColor colorWithRed:0 green:0.5 blue:0.5 alpha:1]; UIColor *LeadColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1]; UIColor *CloverColor = [UIColor colorWithRed:0 green:0.5 blue:0 alpha:1]; UIColor *CayenneColor = [UIColor colorWithRed:0.5 green:0 blue:0 alpha:1]; UIColor *AsparagusColor = [UIColor colorWithRed:0.5 green:0.5 blue:0 alpha:1]; UIColor *MaroonColor = [UIColor colorWithRed:0.5 green:0 blue:0.25 alpha:1]; UIColor *SnowColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1]; NSArray *colorObjects = [NSArray arrayWithObjects:MidNightColor,TealColor,LeadColor,CloverColor,CayenneColor,AsparagusColor,MaroonColor, SnowColor, nil]; NSArray *colorKeys = [NSArray arrayWithObjects:@"Midnight", @"Teal", @"Lead", @"Clover",@"Cayenne", @"Asparagus", @"Maroon", @"Snow", nil]; colorDictionary = [[NSDictionary alloc] initWithObjects:colorObjects forKeys:colorKeys]; return colorDictionary; } @class CanvasView; @interface SimpleSketchAppDelegate : NSObject <UIApplicationDelegate> { CanvasView *aCanvasView; UIView *settingView; UIPickerView *strokeColorPicker; UISlider *strokeSizeSlider; UISlider *strokeAlphaSlider; NSDictionary *colorDictionary; }
  • 64.
  • 65. -(NSInteger) numberOfComponentsInPickerView:(UIPickerView *) pickerView { return 1; } - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { return [[self.colorDictionary allKeys] count]; } -(UIView *) pickerView: (UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *) view { NSString *keyForTheColor = [[self.colorDictionary allKeys] objectAtIndex:row]; UIColor *theColor = [self.colorDictionary valueForKey:keyForTheColor]; UIView *returnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 30)]; UIView *colorView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, 24, 24)]; colorView.backgroundColor = theColor; UILabel *colorNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, 250, 24)]; colorNameLabel.backgroundColor = [UIColor clearColor]; colorNameLabel.font = [UIFont boldSystemFontOfSize:24]; colorNameLabel.text = keyForTheColor; [returnView addSubview:colorView]; [returnView addSubview:colorNameLabel]; [colorView release]; [colorNameLabel release]; [returnView autorelease]; return returnView; } - (void) pickerView: (UIPickerView *) pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { NSString *keyForTheColor = [[self.colorDictionary allKeys] objectAtIndex:row]; UIColor *selectedColor = [self.colorDictionary valueForKey:keyForTheColor]; aCanvasView.strokeColor = selectedColor; }
  • 66. Shake Shake shake Motion event
  • 67. layer path - cgContext 0.7 setNeedsDisplay - layer path (cgContext) -layer - setNeedsDisplay drawRect - (context) - (context) .