如何从矩形叠加中裁剪uiimageView?

时间:2013-04-30 07:34:43

标签: ios crop

我想在我的视图控制器上裁剪一部分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];

所以我知道有什么我错过的,有什么帮助吗?

2 个答案:

答案 0 :(得分:5)

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

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

希望这会对你有所帮助

答案 1 :(得分:4)

您可以使用以下方式获取裁剪图像:

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

希望它对你有所帮助。