gpt4 book ai didi

iphone - 来自 UIView 区域的 UIImage

转载 作者:可可西里 更新时间:2023-11-01 03:12:10 24 4
gpt4 key购买 nike

我正在尝试将 UIView 的区域剪辑到 UIImage 中以供以后重用。

我从一些片段中得出了这段代码:

 CGRect _frameIWant = CGRectMake(100, 100, 100, 100);

UIGraphicsBeginImageContext(view.frame.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];

//STEP A: GET AN IMAGE FOR THE FULL FRAME
UIImage *_fullFrame = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//STEP B: CLIP THE IMAGE
CGImageRef _regionImage = CGImageCreateWithImageInRect([_fullFrame CGImage], _frameIWant);
UIImage *_finalImage = [UIImage imageWithCGImage:_regionImage];
CGImageRelease(_regionImage);

'view' 是我正在剪辑的 UIView_finalImage 是我想要的 UIImage

代码没有问题,但是有点慢。我相信在步骤 A 中直接使用屏幕的一部分可以获得一些性能。

我正在寻找类似 renderInContext: withRect:UIGraphicsGetImageFromCurrentImageContextWithRect() 的东西,呵呵。

还没有找到任何东西:(,如果你知道一些替代方案,请帮助我。

最佳答案

此方法使用较少的内存和 CPU 时间裁剪 View 区域:

-(UIImage*)clippedImageForRect:(CGRect)clipRect inView:(UIView*)view
{
UIGraphicsBeginImageContextWithOptions(clipRect.size, YES, 1.f);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, -clipRect.origin.x, -clipRect.origin.y);
[view.layer renderInContext:ctx];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}

关于iphone - 来自 UIView 区域的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3918890/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com