6

以下代码获取当前屏幕的 UIImage:

    UIGraphicsBeginImageContext(self.view.frame.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self.view.layer renderInContext:ctx];
    UIImage *backgroundImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

如果我有一个 CGRect 矩形并且我只想获取该矩形中当前屏幕的 UIImage,我该怎么办?

4

2 回答 2

15

对于获取矩形(裁剪)图像:

UIImage *croppedImg = nil;
CGRect cropRect = CGRectMake(AS You Need);
croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect];

使用以下返回方法UIImage如您想要的图像大小

- (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect
    {
        //CGRect CropRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height+15);

        CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
        UIImage *cropped = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);

        return cropped;
    }
于 2013-01-23T10:44:31.530 回答
0

传递您要裁剪的图像并根据您的要求更改 image.size.width 和 image.size.height

-(UIImage *)cropSquareImage:(UIImage *)image
{
    CGRect cropRect;

    if (image.size.width < image.size.height)
    {
        float x = 0;
        float y = (image.size.height/2) - (image.size.width/2);

        cropRect = CGRectMake(x, y, image.size.width, image.size.width);
    }
    else
    {
        float x = (image.size.width/2) - (image.size.height/2);
        float y = 0;

        cropRect = CGRectMake(x, y, image.size.height, image.size.height);
    }


    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
    return [UIImage imageWithCGImage:imageRef];


}
于 2013-01-23T10:54:55.037 回答