2

我正在尝试编写一个 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
4

0 回答 0