如何从矩形覆盖中裁剪 uiimageView?

Posted

技术标签:

【中文标题】如何从矩形覆盖中裁剪 uiimageView?【英文标题】:How to crop an uiimageView from a rectangle overlay? 【发布时间】:2013-04-30 07:34:43 【问题描述】:

我想裁剪视图控制器上的 uiimageview 的一部分。我在它上面创建了一个矩形:

        UIGraphicsBeginImageContext(self.view.bounds.size);

        CGContextRef context = UIGraphicsGetCurrentContext();

        CGContextMoveToPoint(context, newPoint1.x, newPoint1.y);
        CGContextAddLineToPoint(context, newPoint1.x, newPoint2.y);
        CGContextAddLineToPoint(context, newPoint2.x, newPoint2.y);
        CGContextAddLineToPoint(context, newPoint2.x, newPoint1.y);
        CGContextAddLineToPoint(context, newPoint1.x, newPoint1.y);
        CGContextClosePath(context);

        UIColor *blue = [UIColor colorWithRed: (0.0/255.0 ) green: (0.0/255.0) blue: (255.0/255.0) alpha:0.4];
        CGContextSetFillColorWithColor(context, blue.CGColor);

        CGContextDrawPath(context, kCGPathFillStroke);

我不知道如何正确裁剪它。我能够检索屏幕的捕获:完全空白,上面有我的矩形:

UIImage *cropImage = UIGraphicsGetImageFromCurrentImageContext();
        rectImage = cropImage;

        UIGraphicsEndImageContext();

        UIImageCrop *rectImageView = [[UIImageCrop alloc]initWithImage:rectImage];

        [self.view addSubview:rectImageView];

所以我知道我错过了一些东西,有什么帮助吗?

【问题讨论】:

【参考方案1】:
- (UIImage *)captureScreenInRect:(CGRect)captureFrame


    CALayer *layer;
    layer = self.view.layer;
    UIGraphicsBeginImageContext(self.view.frame.size); 
    CGContextClipToRect (UIGraphicsGetCurrentContext(),captureFrame);
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenImage;

仅供参考,请根据您的要求更改此代码

希望对你有帮助

【讨论】:

【参考方案2】:

您可以使用以下方法获得裁剪的图像:

- (UIImage*) getCroppedImage 
    CGRect rect = PASS_YOUR_RECT;

    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // translated rectangle for drawing sub image 
    CGRect drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, your_image.size.width, your_image.size.height);

    // clip to the bounds of the image context
    // not strictly necessary as it will get clipped anyway?
    CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height));

    // draw image
    [your_image drawInRect:drawRect];

    // grab image
    UIImage* croppedImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return croppedImage;

希望对你有帮助。

【讨论】:

谢谢,试图理解代码。为什么 rect.origin.x 减去 //translated rectangle ....

以上是关于如何从矩形覆盖中裁剪 uiimageView?的主要内容,如果未能解决你的问题,请参考以下文章

如何获得正确的区域来裁剪 UIImage?

如何在“方面填充”模式下将 UIImageView 裁剪为新的 UIImage?

如何在“方面填充”模式下将 UIImageView 裁剪为新的 UIImage?

UIImageView 捏缩放和重新定位以适应覆盖

查找覆盖原始矩形的旋转矩形的大小

如何在 ImageView 中裁剪 UIImage