아이폰강의(7) pdf
Upcoming SlideShare
Loading in...5
×
 

아이폰강의(7) pdf

on

  • 1,015 views

 

Statistics

Views

Total Views
1,015
Views on SlideShare
1,004
Embed Views
11

Actions

Likes
1
Downloads
16
Comments
0

1 Embed 11

http://www.sunoo.net 11

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    아이폰강의(7) pdf 아이폰강의(7) pdf Presentation Transcript

    • 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 ContextGraphics 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 BlockCurves 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 PathParameterFunction to set parameter value Quartz provides the functions for stroking the current path. SomeLine width are convenience functions for stroking rectangles or ellipses.CGContextSetLineWidth Functions that stroke pathsLine join FunctionCGContextSetLineJoin CGContextStrokePathLine cap Strokes the current path.CGContextSetLineCap CGContextStrokeRectMiter limit Strokes the specified rectangle.CGContextSetMiterLimit CGContextStrokeRectWithWidthLine dash pattern Strokes the specified rectangle, using the specified line width.CGContextSetLineDash CGContextStrokeEllipseInRectStroke 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 currentCGContextSetStrokePattern 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.
    • UIColorTasksCreating 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 + groupTableViewBackgroundColorCreating 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 ProtocolSetting 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 useSetting 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)rowpickerView:viewForRow:forComponent:reusingView: method to provide the content forComponent:(NSInteger)componentof 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: componentCalled 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 ofcomponent. 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 componentrow forComponent:(NSInteger)component reusingView:(UIView *)view row.ParameterspickerViewAn object representing the picker view requesting the data.rowA zero-indexed number identifying a row of component. Rows are numbered top-to-bottom.componentA zero-indexed number identifying a component of pickerView. Components arenumbered left-to-right.viewA view object that was previously used for this row, but is now hidden and cached by thepicker view.Return ValueA 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.CGBitmapContextCreateCreates a bitmap graphics context.CGContextRef CGBitmapContextCreate ( void *data, size_t width, size_t height, size_t bitsPerComponent, size_t bytesPerRow, CGColorSpaceRef colorspace, CGBitmapInfo bitmapInfo);ParametersdataA 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 ownmemory, 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 colorspace, you would specify a value of 8 bits per component. For the list of supported pixel formats, see “Supported Pixel Formats” in the “GraphicsContexts” 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.bitmapInfoConstants that specify whether the bitmap should contain an alpha channel, the alpha channel’s relative location in a pixel, and information aboutwhether the pixel components are floating-point or integer values. The constants for specifying the alpha channel information are declared with theCGImageAlphaInfo 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 theCGBitmapContextCreate function, see “Creating a Bitmap Graphics Context” in the “Graphics Contexts” chapter of Quartz 2D Programming Guide.Return ValueA 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 couldnt 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. IfCGContextDrawImage you are not using a UIView object to do your drawing, however, you must push aDraws 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); CGBitmapContextCreateImageParameters 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 crect );The location and dimensions in user space of the Parametersbounding box in which to draw the image. cimage A bitmap graphics context.The image to draw. Return ValueDiscussion A CGImage object that contains a snapshot of the bitmap graphics context or NULL if the imageQuartz scales the image—disproportionately, if is not created.necessary—to fit the bounds specified by the rect Discussionparameter. 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.CGContextSetAlphaSets the opacity level for objects drawn in a graphics context.void CGContextSetAlpha ( CGContextRef c, CGFloat alpha);ParameterscThe graphics context for which to set the current graphics state’s alpha value parameter.alphaA value that specifies the opacity level. Values can range from 0.0 (transparent) to 1.0 (opaque). Values outside thisrange are clipped to 0.0 or 1.0.DiscussionThis function sets the alpha value parameter for the specified graphics context. To clear the contents of the drawingcanvas, use CGContextClearRect.
    • CGLayerCreateWithContextCreates a CGLayer object that is associated with a graphics context.CGLayerRef CGLayerCreateWithContext ( CGContextRef context, CGSize size, CFDictionaryRef auxiliaryInfo);ParameterscontextThe graphics context you want to create the layer relative to. Thelayer uses this graphics context as a reference for initialization.sizeThe 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 rectReturn Value );A CGLayer object. You are responsible for releasing this object Parametersusing the function CGLayerRelease when you no longer need the clayer. The graphics context in which to paint the rectangle. rectCGLayerGetContext The rectangle, in user space coordinates.Returns the graphics context associated with a CGLayer object. DiscussionCGContextRef CGLayerGetContext ( CGLayerRef layer If the provided context is a window);Parameters or bitmap context, Quartz effectivelylayerThe 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 orThe graphics context associated with the layer. bitmap contexts.DiscussionThe context that’s returned is the context for the layer itself, notthe 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) .