1

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

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

4

2 回答 2

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

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

希望对你有帮助

于 2013-04-30T07:59:57.653 回答
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;
}

希望它可以帮助你。

于 2013-04-30T07:47:03.840 回答