我已经实现了以下代码,允许用户在imageView上绘图。我希望在我的应用程序中实现这一点,但不希望继续复制和粘贴。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
pointCurrent = [touch locationInView:self.view];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint pointNext = [touch locationInView:self.view];
UIGraphicsBeginImageContext(drawImage.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width, drawImage.frame.size.height)];
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, 0.0, 1.0);
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), pointCurrent.x, pointCurrent.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), pointNext.x, pointNext.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
pointCurrent = pointNext;
}
到目前为止,我已尝试创建一个类别,但我不确定这是否是正确的方法。我是否制作了一个自定义方法并尝试在其他类中调用它,或者我正在咆哮错误的树?提前感谢您抽出宝贵时间阅读此问题。
答案 0 :(得分:1)
我稍微修改了你的代码,因为我得到了你在评论中提到的那个错误。这段代码对我有用。
@interface RDImageView ()
@property (nonatomic) CGPoint pointCurrent;
@end
@implementation RDImageView
-(instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
self.userInteractionEnabled = YES;
self.backgroundColor = [UIColor blueColor];
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
self.pointCurrent = [touch locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint pointNext = [touch locationInView:self];
UIGraphicsBeginImageContext(self.frame.size);
[self.image drawInRect:self.bounds];
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1,1, 0.0, 1.0);
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), self.pointCurrent.x, self.pointCurrent.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), pointNext.x, pointNext.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
self.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.pointCurrent = pointNext;
}