在 UIImageView 上绘制 UIBezierPath 用于图像裁剪

Draw UIBezierPath on UIImageView for image crop

我正在开发一个照片编辑应用程序,需要用户能够绘制一条路径来裁剪照片。我有一个 class 与 UIView 一起使用,用于绘制平滑的 UIBezierPath 线。但是我真的需要将它应用于 UIImageView 以便可以在图像上完成绘图。如果我将 class 更改为 subclass UIImageView 而不是它不再有效。关于我可以做些什么来解决这个问题的任何想法?或者实现相同目标的更好选择?下面是我的实现:

    #import "DrawView.h"

@implementation DrawView
{
    UIBezierPath *path;
}

- (id)initWithCoder:(NSCoder *)aDecoder // (1)
{
    if (self = [super initWithCoder:aDecoder])
    {
        [self setMultipleTouchEnabled:NO]; // (2)
        [self setBackgroundColor:[UIColor whiteColor]];
        path = [UIBezierPath bezierPath];
        [path setLineWidth:2.0];
    }
    return self;
}

- (void)drawRect:(CGRect)rect // (5)
{
    [[UIColor blackColor] setStroke];
    [path stroke];
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];
    [path moveToPoint:p];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];
    [path addLineToPoint:p]; // (4)
    [self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesMoved:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesEnded:touches withEvent:event];
}

@end

如果我在 touchesBegan 或 touchesMoved 上放置断点,它会按预期触发。

第一个问题 - userInteractionEnabled 属性 应设置为 YES 以接收触摸事件。

第二个 - drawRect: 方法不为 UIImageView 个子类调用:

The UIImageView class is optimized to draw its images to the display. UIImageView will not call drawRect: a subclass. If your subclass needs custom drawing code, it is recommended you use UIView as the base class.

所以,DrawView 应该是 UIView 子类,它将在 drawRect: 中绘制 UIImage,然后再绘制贝塞尔曲线路径。类似的东西(只改变了部分代码):

// DrawView.h
@interface DrawView : UIView
@property (nonatomic, strong) UIImage* image;
@end

// DrawView.m    
@implementation DrawView

- (void)drawRect:(CGRect)rect
{
    [image drawInRect:self.bounds];
    [[UIColor blackColor] setStroke];
    [path stroke];
}

@end