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
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.
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
.
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.
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.
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.
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.
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.