【问题标题】:How to get UIImage of a specific area in current screen ios如何在当前屏幕ios中获取特定区域的UIImage
【发布时间】:2013-01-06 19:23:44
【问题描述】:

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

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

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

【问题讨论】:

    标签: ios uiimage screen area


    【解决方案1】:

    获取矩形(裁剪)图像:

    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】:

    传递您要裁剪的图像并根据您的要求更改 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);
    • ARC 不适用于 CGImageRef。最后,我的意思是在你返回UIImage之前。
    猜你喜欢
    • 2021-06-24
    • 2016-04-06
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    相关资源
    最近更新 更多