制作一个UIView Canvas,可用于用手指画线

时间:2012-11-20 08:51:52

标签: ios canvas touch draw

我正在尝试编写一个UIView,它就像一个画布,我们可以用手指在它上画画。我实现了CanvasView,当手指移动时,它首先绘制已经存在的图像,然后绘制一条连接前一个点和当前点的小线。当我移动手指时它会绘制图像,但是,当我绘图时,图像会逐渐消失。我不明白为什么会出现这种情况。我知道有一些其他的方法来实现UIView的画布,但我想知道为什么我的工具是错误的。以下是我的完整代码。我希望有人复制这些代码并运行它,然后我的问题可以更直观。

#import <UIKit/UIKit.h>

@interface CanvasView : UIView

@end

#import "CanvasView.h"
#import <QuartzCore/QuartzCore.h>

@interface CanvasView()
@property (nonatomic) CGPoint startPoint;
@property (nonatomic) CGPoint endPoint;
@property (nonatomic, strong) UIImage* oldImage;
@end

@implementation CanvasView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch* touch = [touches anyObject];
    self.startPoint = [touch locationInView:self];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch* touch = [touches anyObject];
    self.endPoint = [touch locationInView:self];

    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    self.oldImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self setNeedsDisplay];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch* touch = [touches anyObject];
    self.endPoint = [touch locationInView:self];

    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    self.oldImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self setNeedsDisplay];
}

-(void)drawRect:(CGRect)rect{
    CGContextRef context = UIGraphicsGetCurrentContext();

    //draw image already exists
    [self.oldImage drawInRect:self.bounds];

    //draw new tiny line
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, self.startPoint.x, self.startPoint.y);
    CGContextAddLineToPoint(context, self.endPoint.x, self.endPoint.y);
    CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
    CGContextSetLineWidth(context, 5.);
    CGContextStrokePath(context);

    self.startPoint = self.endPoint;
}

@end

0 个答案:

没有答案