簡體   English   中英

來自UIView地區的UIImage

[英]UIImage from a region of UIView

我正在嘗試將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:東西renderInContext: withRect:UIGraphicsGetImageFromCurrentImageContextWithRect() hehe。

還沒有找到任何東西:(如果你知道一些替代方案,請幫助我。

此方法使用較少的內存和CPU時間剪切視圖的區域:

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

Swift版本的@ phix23解決方案。 增加規模

func clippedImageForRect(clipRect: CGRect, inView view: UIView) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(clipRect.size, true, UIScreen.mainScreen().scale);
    let ctx = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(ctx, -clipRect.origin.x, -clipRect.origin.y);
    view.layer.renderInContext(ctx!)
    let img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img
}

您可以先嘗試柵格化UIView:

view.layer.shouldRasterize = YES;

我使用它的成功有限,但是說我做的和你一樣(加上上面一行)並且工作正常。 在什么情況下你這樣做? 這可能是您的性能問題。

編輯:您也可以嘗試使用視圖的邊界而不是視圖的框架。 它們並不總是一樣的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM