首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >手绘线时裁剪图像

手绘线时裁剪图像
EN

Stack Overflow用户
提问于 2014-07-19 01:53:30
回答 1查看 661关注 0票数 2

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

我使用下面的方法来绘制线条

代码语言:javascript
运行
复制
- (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];
}

EN

回答 1

Stack Overflow用户

发布于 2014-07-24 23:28:21

试试这个:

代码语言:javascript
运行
复制
@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;
}

这是一个快速编写的代码,所以可能会出错。对此我很抱歉:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24831034

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档