67
Chapter 9 Core Graphics Bit Academy 송진석 2011년 11월 19일 토요일

Chapter 9 Core Graphics

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Chapter 9Core Graphics

Bit Academy 송진석

2011년 11월 19일 토요일

Quartz

Graphics Hardware

Core Graphics

Core AnimationQuartz

Cocoa Touch(UIKit)

Your App

2011년 11월 19일 토요일

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

2011년 11월 19일 토요일

Page• Quartz는 이미지를 painter model로 처리한다.

• 화가의 캔버스에 해당하는 이미지를 그릴수 있는 바탕을 page라 부른다.

• page에 그려지는 이미지는 덧칠하는 형태로 그려지게 된다.

2011년 11월 19일 토요일

Graphics Context

• Graphics Context는 출력장치에 이미지를 그리기 위해 필요한 다음정보를 담고 있다

• 그래픽 관련 변수

• 출력장치 관련 특성정보(해상도, 칼라)

• 그래픽 콘텍스트를 이용함에 의해 이미지를 장치 독립적인 User Space와 Device Space로 분리해서 프로그래머는 개별장치에 대한 고려 없이 그래픽이미지를 사용할 수 있다.

2011년 11월 19일 토요일

Graphics ContextGraphics Context를 사용함에 의해 다양한 출력 장치에 맞는 이미지를 자동으로 출력할 수 있다

Your App

Cocoa Touch(UIKit)

QuartzCore AnimationCore Graphics

Graphics Hardware

2011년 11월 19일 토요일

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

2011년 11월 19일 토요일

Quartz 2D Opaque Data TypesOpaque 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.”

그리기 위한 경로를 표시

이미지 주소

칼라 표현방식에 대한 참조

2011년 11월 19일 토요일

Graphics States

• Graphics State는 현재 드로잉시에 사용되는 드로잉 파라미터를 의미한다.

• Graphics Context는 Graphics State를 저장하기 위한 스택을 유지하고 현재 상태를 저장해서 스택에 집어넣고 다른상태를 사용후 복원해서 사용할 수 있다.

• CGContextSaveGState, CGContextRestoreGState는 그래픽 스테이트를 저장하고 꺼내는 함수이다.

2011년 11월 19일 토요일

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”

2011년 11월 19일 토요일

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.

2011년 11월 19일 토요일

Quartz 2D Coordinate Systems

2011년 11월 19일 토요일

Pathpath는그리려고 하는 하나이상의 모양을 나타낸다 Path는 직선, 곡선으로 이루어져 있고 열려있거나 닫혀있을 수 있다.

2011년 11월 19일 토요일

Path Building BlockPointsPoints 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.

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

ArcsArcs are circle segments. Quartz provides two functions that create arcs. The function CGContextAddArc creates a curved segment from a circle.

2011년 11월 19일 토요일

Path Building BlockFigure 3-7  A cubic Bézier curve uses two control points

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.

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

Curves

2011년 11월 19일 토요일

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 를 사용한다.

2011년 11월 19일 토요일

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.

2011년 11월 19일 토요일

Stroke  Parameters that affect how Quartz strokes the current pathParameterFunction to set parameter valueLine widthCGContextSetLineWidthLine joinCGContextSetLineJoinLine capCGContextSetLineCapMiter limitCGContextSetMiterLimitLine dash patternCGContextSetLineDashStroke color spaceCGContextSetStrokeColorSpaceStroke colorCGContextSetStrokeColorCGContextSetStrokeColorWithColorStroke patternCGContextSetStrokePattern

Functions for Stroking a PathQuartz provides the functions for stroking the current path. Some are convenience functions for stroking rectangles or ellipses.

Functions that stroke pathsFunctionCGContextStrokePathStrokes the current path.CGContextStrokeRectStrokes the specified rectangle.CGContextStrokeRectWithWidthStrokes the specified rectangle, using the specified line width.CGContextStrokeEllipseInRectStrokes an ellipse that fits inside the specified rectangle.CGContextStrokeLineSegments:Strokes a sequence of lines.CGContextDrawPath :If you pass the constant kCGPathStroke, strokes the current path. See “Filling a Path” if you want to both fill and stroke a path.

2011년 11월 19일 토요일

Fill Functions that fill pathsFunctionDescriptionCGContextEOFillPathFills the current path using the even-odd rule.CGContextFillPathFills the current path using the nonzero winding number rule.CGContextFillRectFills the area that fits inside the specified rectangle.CGContextFillRectsFills the areas that fits inside the specified rectangles.CGContextFillEllipseInRectFills an ellipse that fits inside the specified rectangle.CGContextDrawPathFills 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.

2011년 11월 19일 토요일

Color and Color Spaces

Color : 특정색을 나타냄 color space에 의존적Color Space: 색을 표현하기 위한 체계

출력장치마다 칼라를 표현하는 방식이나 표현 범위가 달라 User Space에서 표현된 칼라를 device color체계로 매핑하기 위한 설정이 필요한다.

Table 4-1  Color values in different color spacesValues

value color space components

240 degrees, 100%, 100% HSB

Hue, saturation, brightness

0, 0, 1 RGBRed, green, blue

1, 1, 0, 0CMYK

Cyan, magenta, yellow, black

1, 0, 0 BGR Blue, green, red

2011년 11월 19일 토요일

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.

2011년 11월 19일 토요일

About Quartz Transformation Functions

User Space의 이차원 좌표계내에서 이미지 대상을 translate(이동), rotate(회전), scale(확대, 축소)할 수 있다.Graphic Context가 생성될때 상태를 표시하는 3차원 CTM(Current Transformation Matrix)이 정의되고 아무런 변형 작업이 이루어 지지 않았으므로 identity matrix로 초기화되어 있다.

2011년 11월 19일 토요일

TransformationCGContextTranslateCTM (myContext, w/4, 0);

CGContextScaleCTM (myContext, .25, .5);

CGContextRotateCTM (myContext, radians ( 22.));

2011년 11월 19일 토요일

Creating Affine TransformsThe 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 scalingFunctioCGAffineTransformMakeTranslationTo construct a new translation matrix from x and y values that specify how much to move the origin.CGAffineTransformTranslateTo apply a translation operation to an existing affine transform.CGAffineTransformMakeRotationTo construct a new rotation matrix from a value that specifies in radians how much to rotate the coordinate system.CGAffineTransformRotateTo apply a rotation operation to an existing affine transform.CGAffineTransformMakeScaleTo construct a new scaling matrix from x and y values that specify how much to stretch or shrink coordinates.CGAffineTransformScaleTo apply a scaling operation to an existing affine transform.

2011년 11월 19일 토요일

코아그래픽스사전지식

• 코어그래픽스는 C API

✴ 그래픽 함수에 Create가 포함되면 CGContextRelese(Context)와 같은 릴리이즈 함수를 이용해 릴리즈해주어야 한다.

✴ 그래픽함수에 Get이 들어간 경우는 릴리즈를 안해주어도 된다.

• 비트맵과 벡터

✴ 비트맵 : 그림이 그려질 공간을 점으로 구성된 공간으로 설정후 각각의 점에 대한 컬러값을 조정해서 그림을 표현

✴ 벡터 : 그림이 그려질 공간을 좌표로 표현하고 위치값을 이용하여 직선이나 곡선을 이용하여 그림을 그린다.

• 컬러스페이스

✴ 가법혼합식, 아이폰에서 사용하는 컬러스페이스 CGColorSpaceCreateDeviceRGB

• 선형대수

✴ 코어그래픽스에는 Affine Transform을 이용해서 도형의 확대/축소, 이동, 회전, 기울이기등을 수행함으로 행렬관련 지식을 필요로 한다.

2011년 11월 19일 토요일

UIResponder Class

Managing the Responder Chain1 – nextResponder2 – isFirstResponder3 – canBecomeFirstResponder4 – becomeFirstResponder5 – canResignFirstResponder6 – resignFirstResponder

Managing Input Views1   inputView  property2   inputAccessoryView  property3 – reloadInputViews

Responding to Touch Events1 – touchesBegan:withEvent:2 – touchesMoved:withEvent:3 – touchesEnded:withEvent:4 – touchesCancelled:withEvent:

Responding to Motion Events1 – motionBegan:withEvent:2 – motionEnded:withEvent:3 – motionCancelled:withEvent:

Responding to Remote-Control Events1 – remoteControlReceivedWithEvent:

Getting the Undo Manager1   undoManager  property

Validating Commands1 – canPerformAction:withSender:

motionBegan:withEvent:Tells the receiver that a motion event has begun.

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)eventParametersmotionAn event-subtype constant indicating the kind of motion. A common motion is shaking, which is indicated by UIEventSubtypeMotionShake.eventAn object representing the event associated with the motion.DiscussioniOS informs the first responder only when a motion event starts and when it ends; for example, it doesn’t report individual shakes. The receiving object must be the first responder to receive motion events.

The default implementation of this method does nothing. However immediate UIKit subclasses of UIResponder, particularly UIView, forward the message up the responder chain.

2011년 11월 19일 토요일

UITouch ClassGetting the Location of Touches1 – locationInView:2 – previousLocationInView:3   view  property4   window  property

Getting Touch Attributes1   tapCount  property2   timestamp  property3   phase  property

Getting a Touch Object’s Gesture Recognizers1   gestureRecognizers  property

gestureRecognizersThe gesture recognizers that are receiving the touch object.

@property(nonatomic,readonly,copy) NSArray *gestureRecognizersDiscussionThe objects in the array are instances of a subclass of the abstract base class UIGestureRecognizer. If there are no gesture recognizers currently receiving the touch objects, this property holds an empty array.

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

2011년 11월 19일 토요일

UIEvent ClassUIEvent는 이벤트를 나타내는데 세가지 종류가 있다

- 터치 이벤트

- 모션이벤트

- 리모트콘트롤 이벤트 : 악세서리 장치에서오는 이벤트 볼룸 업/다운, 플레이 비디오 기타 등등

터치 타입 이벤트는 한개 또는 이상의 터치를 포함하며 Responder의 메소드에 전달한다.

해당 메소드에서 터치 정보를 터치 페이즈, 윈도우, 뷰, 시간별로 분석하여 처리를 수행한다.

이벤트에 타입과 서브타입이 있으며 모션 이벤트의 서브타입은 shake가 있고 remote-control 이벤트의 서브타입은 play, previous track이 있으며 각 해당 메소드가 존재한다.

motionBegan:withEvent: , remoteControlReceivedWithEvent:

Getting the Touches for an Event1 – allTouches2 – touchesForView:3 – touchesForWindow:

Getting Event Attributes1   timestamp  property

Getting the Event Type1   type  property2   subtype  property

Getting the Touches for a Gesture Recognizer1 – touchesForGestureRecognizer:

subtypeReturns the subtype of the event. (read-only)

@property(readonly) UIEventSubtype subtypeDiscussionThe 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.

typedef enum { UIEventSubtypeNone = 0, UIEventSubtypeMotionShake = 1, UIEventSubtypeRemoteControlPlay = 100, UIEventSubtypeRemoteControlPause = 101, UIEventSubtypeRemoteControlStop = 102, UIEventSubtypeRemoteControlTogglePlayPause = 103, UIEventSubtypeRemoteControlNextTrack = 104, UIEventSubtypeRemoteControlPreviousTrack = 105, UIEventSubtypeRemoteControlBeginSeekingBackward = 106, UIEventSubtypeRemoteControlEndSeekingBackward = 107, UIEventSubtypeRemoteControlBeginSeekingForward = 108, UIEventSubtypeRemoteControlEndSeekingForward = 109,} UIEventSubtype;

typeReturns the type of the event. (read-only)

@property(readonly) UIEventType type

typedef enum { UIEventTypeTouches, UIEventTypeMotion, UIEventTypeRemoteControl,} UIEventType;allTouches

Returns all touch objects associated with the receiver.

- (NSSet *)allTouchesReturn ValueA set of UITouch objects representing all touches associated with an event (represented by the receiver).

DiscussionIf the touches of the event originate in different views and windows, the UITouch objects obtained from this method will have different responder objects associated with the touches.

2011년 11월 19일 토요일

CGColor

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

const CGFloat * CGColorGetComponents ( CGColorRef color);ParameterscolorA Quartz color.Return ValueAn 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.

2011년 11월 19일 토요일

UIColor

CGColorThe Quartz color reference that corresponds to the receiver’s color. (read-only)

@property(nonatomic,readonly) CGColorRef CGColor

TasksCreating a UIColor Object from Component Values1 + colorWithWhite:alpha:2 + colorWithHue:saturation:brightness:alpha:3 + colorWithRed:green:blue:alpha:4 + colorWithCGColor:5 + colorWithPatternImage:6 – colorWithAlphaComponent:

Initializing a UIColor Object1 – initWithWhite:alpha:2 – initWithHue:saturation:brightness:alpha:3 – initWithRed:green:blue:alpha:4 – initWithCGColor:5 – initWithPatternImage:

Creating a UIColor with Preset Component Values1 + blackColor2 + darkGrayColor3 + lightGrayColor4 + whiteColor5 + grayColor6 + redColor7 + greenColor8 + blueColor9 + cyanColor10 + yellowColor11 + magentaColor12 + orangeColor13 + purpleColor14 + brownColor15 + clearColor

System Colors1 + lightTextColor2 + darkTextColor3 + groupTableViewBackgroundColor4 + viewFlipsideBackgroundColor5 + scrollViewTexturedBackgroundColor

Retrieving Color Information1   CGColor  property

Drawing Operations1 – set2 – setFill3 – setStroke

2011년 11월 19일 토요일

View Animation

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

+ (void)beginAnimations:(NSString *)animationID context:(void *)contextParametersanimationIDAn application-supplied identifier for the animations.contextCustom 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.DiscussionUse 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.

2011년 11월 19일 토요일

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)cacheParameterstransitionA transition to apply to view. Possible values are described in UIViewAnimationTransition.viewThe view to apply the transition to.cacheIf 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.DiscussionUse 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.

2011년 11월 19일 토요일

View Animation

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

+ (void)commitAnimationsDiscussionUse 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.

2011년 11월 19일 토요일

PickerView ClassTasksGetting the Dimensions of the View Picker1   numberOfComponents  property2 – numberOfRowsInComponent:3 – rowSizeForComponent:

Reloading the View Picker1 – reloadAllComponents2 – reloadComponent:

Selecting Rows in the View Picker1 – selectRow:inComponent:animated:2 – selectedRowInComponent:

Returning the View for a Row and Component1 – viewForRow:forComponent:

Specifying the Delegate1   delegate  property

Specifying the Data Source1   dataSource  property

Managing the Appearance of the Picker View1   showsSelectionIndicator  property

2011년 11월 19일 토요일

PickerView DataSource ProtocolTasksProviding Counts for the Picker View1 – numberOfComponentsInPickerView:2 – pickerView:numberOfRowsInComponent:

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

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerViewParameterspickerViewThe picker view requesting the data.Return ValueThe 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)componentParameterspickerViewThe picker view requesting the data.componentA zero-indexed number identifying a component of pickerView. Components are numbered left-to-right.

2011년 11월 19일 토요일

PickerView Delegate ProtocolSetting the Dimensions of the Picker View1 – pickerView:rowHeightForComponent:2 – pickerView:widthForComponent:

Setting the Content of Component RowsThe methods in this group are marked @optional. However, to use a picker view, you must implement either the pickerView:titleForRow:forComponent: or the pickerView:viewForRow:forComponent:reusingView: method to provide the content of component rows.

1 – pickerView:titleForRow:forComponent:2 – pickerView:viewForRow:forComponent:reusingView:

Responding to Row Selection1 – pickerView:didSelectRow:inComponent:

pickerView:titleForRow:forComponent:Called by the picker view when it needs the title to use for a given row in a given component.

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)componentParameterspickerViewAn 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 are numbered left-to-right.Return ValueThe string to use as the title of the indicated component row.

pickerView:viewForRow:forComponent:reusingView:Called by the picker view when it needs the view to use for a given row in a given component.

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)viewParameterspickerViewAn 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 are numbered left-to-right.viewA view object that was previously used for this row, but is now hidden and cached by the picker 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.

2011년 11월 19일 토요일

NSDictionary ClassinitWithObjects:forKeys:Initializes a newly allocated dictionary with entries constructed from the contents of the objects and keys arrays.

- (id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keysParametersobjectsAn array containing the values for the new dictionary.keysAn 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.DiscussionThis 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.

allKeysReturns a new array containing the dictionary’s keys.

- (NSArray *)allKeysReturn ValueA new array containing the dictionary’s keys, or an empty array if the dictionary has no entries.

DiscussionThe order of the elements in the array is not defined.

2011년 11월 19일 토요일

UIAlertView Class

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

- (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...ParameterstitleThe string that appears in the receiver’s title bar.messageDescriptive text that provides more details than the title.delegateThe receiver’s delegate or nil if it doesn’t have a delegate.cancelButtonTitleThe 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 ValueNewly initialized alert view.

showDisplays the receiver using animation.

- (void)show

2011년 11월 19일 토요일

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)buttonIndexParametersalertViewThe alert view containing the button.buttonIndexThe position of the clicked button. The button indices start at 0.DiscussionThe receiver is automatically dismissed after this method is invoked.

2011년 11월 19일 토요일

예제 프로그램

캔버스뷰만들기

컨택스트초기화

터치이벤트처리

뷰그리기

멀티터치옵션

2011년 11월 19일 토요일

캔버스뷰 만들기#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;}

window based application CanvasView클래스 생성

2011년 11월 19일 토요일

컨텍스트초기화하기- (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;}

@interface CanvasView : UIView { CGContextRef cgContext; }

@end

CanvasView.h

CanvasView.m

흰색으로 세팅

2011년 11월 19일 토요일

CGColorSpaceCreateDeviceRGBCreates a device-dependent RGB color space.

CGColorSpaceRef CGColorSpaceCreateDeviceRGB(void);Return ValueA 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 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.bitmapInfoConstants 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 ValueA new bitmap context, or NULL if a context could not be created. You are responsible for releasing this object using CGContextRelease.

2011년 11월 19일 토요일

컨텍스트초기화하기initWithFrame:Initializes and returns a newly allocated view object with the specified frame rectangle.

- (id)initWithFrame:(CGRect)aRectParametersaRectThe 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 ValueAn initialized view object or nil if the object couldn't be created.

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

View를 생성하는 초기화 메소드 여기서 비트맴콘텍스트를 세팅해서 뷰에 그릴 이미지의 칼라나 라인등을 설정한다.

2011년 11월 19일 토요일

터치이벤트받기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:가 호출된다.

2011년 11월 19일 토요일

뷰그리기- (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)); CGContextBeginPath(cgContext); CGContextMoveToPoint(cgContext, preLocation.x, preLocation.y); CGContextAddLineToPoint(cgContext, location.x, location.y); CGContextStrokePath(cgContext); } [self setNeedsDisplay];}

cgContext 비트맵콘텍스트에 패스를 그리기 시작할 것을 선언

preLocation에서 그릴 선의 시작점을 나타냄

Location에서 그릴 선의 종착점을 나타냄

시작점과 종착점 사이에 라인을 비트맵 콘텍스트에 그림

CanvasView에 비트맵콘트스트의 내용을 적당한 시기에 그리도록 함

-drawRect:를 호출하여 그림

2011년 11월 19일 토요일

뷰그리기UIGraphicsGetCurrentContextReturns the current graphics context.

CGContextRef UIGraphicsGetCurrentContext ( void);Return ValueThe current graphics context.

DiscussionThe 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 you are not using a UIView object to do your drawing, however, you must push a valid context onto the stack manually using the UIGraphicsPushContext function.

You should call this function from the main thread of your application only.

- (void)drawRect:(CGRect)rect{ // Drawing code CGRect bounds = [self bounds]; CGContextRef context = UIGraphicsGetCurrentContext(); CGImageRef image = CGBitmapContextCreateImage(cgContext); CGContextDrawImage(context, bounds, image); CGImageRelease(image);}

CGBitmapContextCreateImageCreates and returns a Quartz image from the pixel data in a bitmap graphics context.

CGImageRef CGBitmapContextCreateImage ( CGContextRef c);ParameterscA bitmap graphics context.Return ValueA CGImage object that contains a snapshot of the bitmap graphics context or NULL if the image is not created.

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

CGContextDrawImageDraws an image into a graphics context.

void CGContextDrawImage ( CGContextRef c, CGRect rect, CGImageRef image);ParameterscThe graphics context in which to draw the image.rectThe location and dimensions in user space of the bounding box in which to draw the image.imageThe image to draw.DiscussionQuartz scales the image—disproportionately, if necessary—to fit the bounds specified by the rect parameter.

2011년 11월 19일 토요일

멀티터치확장하기- (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;}

다수의 손가락으로 터치한 경우에도 각각의 터치에 대해 선을 그린다.

2011년 11월 19일 토요일

코어그래픽스 레이어

• 비트맵컨텍스트에 그린 그림을 컨버스뷰의 콘텍스트에 옮겨 그림(이전방식)

• CGLayer객체를 활용하면 비디오메모리 캐싱이 가능해서 빠르고 효율적으로 작동(새로운 적용), 반복적인 이미지를 사용하는 경우

2011년 11월 19일 토요일

CGLayer만들기@interface CanvasView : UIView { 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{ UITouch *touch; for (touch in touches) { CGPoint location = [touch locationInView:self]; CGPoint preLocation = [touch previousLocationInView:self]; NSLog(@"PrevLoc = %@, Loc = %@", NSStringFromCGPoint(preLocation), NSStringFromCGPoint(location)); CGContextRef context = CGLayerGetContext(cgLayer); CGContextBeginPath(context); CGContextMoveToPoint(context, preLocation.x, preLocation.y); CGContextAddLineToPoint(context, location.x, location.y); CGContextStrokePath(context); } [self setNeedsDisplay];}

비트맵콘텍스트에 관련된 레이어를 생성함

생성된 레이어에 대해 콘텍스트를 생성함

레이어 콘텍스트에 변수를 셋팅

레이어 콘텍스트에 라인을 그림

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ CGRect bounds = [self bounds]; CGContextSetAlpha(cgContext, 0.7); CGContextDrawLayerInRect(cgContext, bounds, cgLayer); CGContextClearRect(CGLayerGetContext(cgLayer), bounds); [self setNeedsDisplay];}

레이어에 그린 그림을 지워 초기화함

레이어에 그려진 그림을 비트맵콘텍스트에 그림

비트맵콘텍스트의 투명도를 0.7로 세팅

- (void)drawRect:(CGRect)rect{ // Drawing code CGRect bounds = [self bounds]; CGContextRef context = UIGraphicsGetCurrentContext(); CGImageRef image = CGBitmapContextCreateImage(cgContext); CGContextDrawImage(context, bounds, image); CGImageRelease(image); CGContextSetAlpha(context, 0.7); CGContextDrawLayerInRect(context, bounds, cgLayer);}

터치엔드가 일어나기 전에 레이어에 그려진 선을 화면에 표시함

터치엔드가 일어나면 레이어에는 아무그림도 없음

2011년 11월 19일 토요일

CGContextDrawLayerInRectDraws the contents of a CGLayer object into the specified rectangle.

void CGContextDrawLayerInRect ( CGContextRef context, CGRect rect, CGLayerRef layer);ParameterscontextThe graphics context associated with the layer.rectThe rectangle, in current user space coordinates, to draw to.layerThe layer whose contents you want to draw.DiscussionThe 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 this range 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 drawing canvas, use CGContextClearRect.

2011년 11월 19일 토요일

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. The layer uses this graphics context as a reference for initialization.sizeThe size, in default user space units, of the layer relative to the graphics context.auxiliaryInfoReserved for future use. Pass NULL.Return ValueA CGLayer object. You are responsible for releasing this object using the function CGLayerRelease when you no longer need the layer.

CGLayerGetContextReturns the graphics context associated with a CGLayer object.

CGContextRef CGLayerGetContext ( CGLayerRef layer);ParameterslayerThe layer whose graphics context you want to obtain.Return ValueThe graphics context associated with the layer.

DiscussionThe context that’s returned is the context for the layer itself, not the context that you specified when you created the layer.

CGContextClearRectPaints a transparent rectangle.

void CGContextClearRect ( CGContextRef c, CGRect rect);ParameterscThe graphics context in which to paint the rectangle.rectThe rectangle, in user space coordinates.Discussion

If the provided context is a window or bitmap context, Quartz effectively clears the rectangle. For other context types, Quartz fills the rectangle in a device-dependent manner. However, you should not use this function in contexts other than window or bitmap contexts.

2011년 11월 19일 토요일

부가기능구현

프라퍼티만들고KVO설정 UI구성하기

뷰플립과 스트로크슬라이더구성

피커뷰데이터소스&

델리게이트구현Shake이벤트처리하기

콘텍스트 상태변수를 세팅하기위한 클래스변수를 KVO세팅을 하고 이들변수값을 변경시 자동으로 콘텍스트에 설정이 이루어지도록한다.

콘텍스트 상태변수에 설정하기위한 UI를 IB를 이용하여 만든다

2011년 11월 19일 토요일

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]; }}

2011년 11월 19일 토요일

- (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);}

@interface CanvasView (Private)

-(void) updateStrokeColor;-(void) updateStrokeSize;

@end

CanvasView.m 화일에 @implementation전에 카티고리로 선언해서 클래스를 확장

- (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;}

2011년 11월 19일 토요일

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

const CGFloat * CGColorGetComponents ( CGColorRef color);ParameterscolorA Quartz color.Return ValueAn 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.

CGColor Reference에 정의

2011년 11월 19일 토요일

CGContextSetRGBStrokeColorSets the current stroke color to a value in the DeviceRGB color space.

void CGContextSetRGBStrokeColor ( CGContextRef c, CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha);ParameterscThe graphics context for which to set the current stroke color.redThe red intensity value for the color to set. The DeviceRGB color space permits the specification of a value ranging from 0.0 (zero intensity) to 1.0 (full intensity).greenThe green intensity value for the color to set. The DeviceRGB color space permits the specification of a value ranging from 0.0 (zero intensity) to 1.0 (full intensity).blueThe blue intensity value for the color to set. The DeviceRGB color space permits the specification of a value ranging from 0.0 (zero intensity) to 1.0 (full intensity).alphaA 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.DiscussionWhen you call this function, two things happen:

• Quartz sets the current stroke color space to DeviceRGB.• Quartz sets the current stroke color to the value specified by the red, green, blue, and alpha parameters.

2011년 11월 19일 토요일

UI 구성하기콘텍스트의 그래픽상태변수(stroke size, alpha, color)를 설정하기 위한 화면구성

2011년 11월 19일 토요일

아웃렛 액션연결#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;

@end

@implementation SimpleSketchAppDelegate

@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{ }

2011년 11월 19일 토요일

뷰플립과 스트로그슬라이더구현

2011년 11월 19일 토요일

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사용자가 특정컴포넌트의 로우를 선택한 경우 호출되는 메소드

2011년 11월 19일 토요일

컬러데이타만들기

-(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;

}

2011년 11월 19일 토요일

피커뷰아웃렉설정

2011년 11월 19일 토요일

-(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;}

2011년 11월 19일 토요일

Shake 이벤트 처리Shake이벤트를 사용하면 기기를 사용자가 흔들면 이를 인식할 수 있다shake 이벤트는 Motion event의 일종

2011년 11월 19일 토요일

투명선그리는 문제터치엔드터치무브

layer 콘텍스트에 path 그림setNeedsDisplay 호출

- cgContext의 알파를 0.7로 셋- layer 콘텍스트의 path를 비트맵콘택스트(cgContext)에 그림-layer콘텍스트의 그림을 지움- setNeedsDisplay 호출

레이어에 패스그림레이어의 패스를 비트맵에 옮기고

레이어의 패스를 지움

- 비트맵콘텍스트의 이미지를 화면(context)에 그림- 레이어콘텍스트의 이미지를 화면(context)에 그림

drawRect터치가 움직이는 동안에 연속적으로 불려 선이 그려짐터치엔드가 되면 터치엔드메소드가 호출되고 레이어의 패스가 비트맵 콘텍스트로 옮겨가고 레이어의 패스

는 지워짐새로추가된 선을 포함한 비트맵 콘텍스트가 그려지고 빈 레이어 콘텍스트가 화면

에 그려진다.

비트맵콘텍스트는 레이어에서 옮겨 그려진 선이 누적되어 그려짐

2011년 11월 19일 토요일