gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:39:59 24 4
gpt4 key购买 nike

我正在开发一个照片编辑应用程序,需要用户能够绘制一条路径来裁剪照片。我有一个与 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 以接收触摸事件。

第二个 - 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,在 bezier 路径之前绘画。类似的东西(只改变了部分代码):

// 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

关于ios - 在 UIImageView 上绘制 UIBezierPath 用于图像裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32544217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com