如何在当前屏幕上获取特定区域的UIImage(iOS)

6
下面的代码获取当前屏幕的UIImage:
    UIGraphicsBeginImageContext(self.view.frame.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self.view.layer renderInContext:ctx];
    UIImage *backgroundImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

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

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

2
太好了!我想点赞以示感谢,但我没有足够的声望。 - thomasdao

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


}

你的 imageRef 会泄漏内存,你需要在结尾处加上 CGImageRelease(imageRef); - WDUK
ARC不适用于CGImageRef。在最后,即在返回UIImage之前,请注意。 - WDUK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接