gpt4 book ai didi

ios - 用手画线时裁剪图像

转载 作者:行者123 更新时间:2023-12-01 16:16:09 33 4
gpt4 key购买 nike

我在 View 上添加了一个 ImageView 。 View 正在使用 UIBezierPath和触摸响应方法,用于在屏幕上拖动时绘制线条。现在我想剪裁线下方的图像部分。我怎样才能做到这一点。

我使用以下方法画线

- (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];
}

enter image description here

最佳答案

试试这个:

@property (strong, nonatomic) UIBezierPath *bezierPath;
//...

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

self.bezierPath = [UIBezierPath bezierPath];
[self.bezierPath moveToPoint:p];
}

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

[self.bezierPath addLineToPoint:p];
}

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

// Here you can call -croppedImage; method and get the image you need.
}

- (UIImage *)croppedImage
{
[self.bezierPath closePath];

UIImage *image = //Your initial image;

CGSize imageSize = image.size;
CGRect imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height);

UIGraphicsBeginImageContextWithOptions(imageSize, NO, [[UIScreen mainScreen] scale]);
// Create the clipping path and add it
[self.bezierPath addClip];
[image drawInRect:imageRect];
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return croppedImage;
}

这是一个快速编写的代码,因此可能会出现错误。对此感到抱歉:)

关于ios - 用手画线时裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24831034/

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