-------------------------------h
@interfaceDoodleView :UIView
{
CGContextRefcontext;
CGLayerReflayer;
floatbrushWidth;
floatbrushColor;
}
@property(nonatomic,assign)floatbrushWith;
@end
-----------------------------------m
#import"DoodleView.h"
@implementationDoodleView
- (id)initWithFrame:(CGRect)frame
{
self= [superinitWithFrame:frame];
if(self) {
self.backgroundColor= [UIColorwhiteColor];
CGColorSpaceRefcolorSpace =CGColorSpaceCreateDeviceRGB();
context=CGBitmapContextCreate(NULL,self.frame.size.width,self.frame.size.height, 8, 4 *self.frame.size.width, colorSpace,kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
layer=CGLayerCreateWithContext(context,self.frame.size,NULL);
CGContextReflayerContext =CGLayerGetContext(layer);
if(brushWidth==0.0) {
brushWidth= 1.0;
}else{
brushWidth=_brushWith;
}
CGContextSetLineWidth(layerContext,brushWidth);
CGContextSetLineCap(layerContext,kCGLineCapRound);
CGContextSetRGBFillColor(layerContext,brushColor,brushColor,brushColor, 1);
}
returnself;
}
-(void)setsize
{
}
- (void)drawRect:(CGRect)rect
{
CGContextRefcurrentContext =UIGraphicsGetCurrentContext();
CGImageRefimageRef =CGBitmapContextCreateImage(context);
CGContextDrawImage(currentContext, [selfbounds], imageRef);
CGImageRelease(imageRef);
CGContextDrawLayerInRect(currentContext, [selfbounds],layer);
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
UITouch*touch = [touchesanyObject];
if([touchtapCount] == 2) {
CGContextClearRect(context, [selfbounds]);
[selfsetNeedsDisplay];
}else{
[selftouchesMoved:toucheswithEvent:event];
}
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
UITouch*touch = [touchesanyObject];
CGPointlocation = [touchlocationInView:self];
CGPointpastLocation = [touchpreviousLocationInView:self];
CGContextReflayerContext =CGLayerGetContext(layer);
CGContextBeginPath(layerContext);
CGContextMoveToPoint(layerContext, pastLocation.x, pastLocation.y);
CGContextAddLineToPoint(layerContext, location.x, location.y);
CGContextStrokePath(layerContext);
[selfsetNeedsDisplay];
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
CGContextDrawLayerInRect(context, [selfbounds],layer);
CGContextClearRect(context, [selfbounds]);
}
- (void)dealloc
{
CGContextRelease(context);
CGLayerRelease(layer);
[superdealloc];
}
@end