簡體   English   中英

在UIImageView上繪制UIBezierPath進行圖像裁剪

[英]Draw UIBezierPath on UIImageView for image crop

我正在使用照片編輯應用程序,需要用戶能夠繪制出裁剪照片的路徑。 我有一個與UIView一起使用的類,用於繪制平滑的UIBezierPath線。 但是,我確實需要將此應用到UIImageView,以便可以在圖像上進行繪制。 如果我將類更改為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以接收觸摸事件。

第二個UIImageView子類未調用drawRect:方法:

UIImageView類經過優化,可以將其圖像繪制到顯示器上。 UIImageView不會調用drawRect:一個子類。 如果您的子類需要自定義繪圖代碼,則建議您使用UIView作為基類。

因此, DrawView應該是UIView子類,它將在繪制bezier路徑之前在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM