2014-05-01 83 views
1

我試圖清除當我按下按鈕時繪製的內容。但是,我似乎無法弄清楚如何去做。我有谷歌周圍的升技,它似乎你需要在繪製矩形內做到這一點。這是我使用的全碼:如何刪除UIView(Core Graphics)的內容?

#import "PaintView.h" 

@implementation PaintView 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     hue = 0.0; 
     [self initContext:frame.size]; 
    } 
    return self; 
} 

- (BOOL) initContext:(CGSize)size { 

    int bitmapByteCount; 
    int bitmapBytesPerRow; 

    // Declare the number of bytes per row. Each pixel in the bitmap in this 
    // example is represented by 4 bytes; 8 bits each of red, green, blue, and 
    // alpha. 
    bitmapBytesPerRow = (size.width * 4); 
    bitmapByteCount = (bitmapBytesPerRow * size.height); 

    // Allocate memory for image data. This is the destination in memory 
    // where any drawing to the bitmap context will be rendered. 
    self.cacheBitmap = malloc(bitmapByteCount); 
    if (self.cacheBitmap == NULL){ 
     return NO; 
    } 
    self.cacheContext = CGBitmapContextCreate (self.cacheBitmap, size.width, size.height, 8, bitmapBytesPerRow, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst); 
    return YES; 
} 

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 

    UITouch *touch = [touches anyObject]; 
    [self drawToCache:touch]; 
} 

- (void) drawToCache:(UITouch*)touch { 
    hue += 0.005; 
    if(hue > 1.0) hue = 0.0; 
    UIColor *color = [UIColor colorWithHue:hue saturation:0.7 brightness:1.0 alpha:1.0]; 

    CGContextSetStrokeColorWithColor(self.cacheContext, [color CGColor]); 
    CGContextSetLineCap(self.cacheContext, kCGLineCapRound); 
    CGContextSetLineWidth(self.cacheContext, 6); 

    CGPoint lastPoint = [touch previousLocationInView:self]; 
    CGPoint newPoint = [touch locationInView:self]; 

    CGContextMoveToPoint(self.cacheContext, lastPoint.x, lastPoint.y); 
    CGContextAddLineToPoint(self.cacheContext, newPoint.x, newPoint.y); 
    CGContextStrokePath(self.cacheContext); 

    CGRect dirtyPoint1 = CGRectMake(lastPoint.x-10, lastPoint.y-10, 20, 20); 
    CGRect dirtyPoint2 = CGRectMake(newPoint.x-10, newPoint.y-10, 20, 20); 
    [self setNeedsDisplayInRect:CGRectUnion(dirtyPoint1, dirtyPoint2)]; 
} 

-(void)clear{ 
// this doesn't work. 
    CGContextClearRect(self.context, self.bounds); 
} 

- (void) drawRect:(CGRect)rect { 
    self.context = UIGraphicsGetCurrentContext(); 
    CGImageRef cacheImage = CGBitmapContextCreateImage(self.cacheContext); 
    CGContextDrawImage(self.context, self.bounds, cacheImage); 
    CGImageRelease(cacheImage); 
    CGContextRetain(self.context); 
} 

@end 

回答

0

按鈕應該調用哪個強制的drawRect被稱爲或基本強制重繪視圖的setNeedsDisplay方法。

+0

謝謝,也發現了 – user3534757