代码之家  ›  专栏  ›  技术社区  ›  Ale Morales

来自UIView区域的UIImage

  •  8
  • Ale Morales  · 技术社区  · 15 年前

    我试着剪辑一个 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);
    

    UIView公司 我正在剪辑和 _finalImage UIImage公司

    代码可以正常工作,但是有点慢。我相信,在步骤A中,只要直接使用屏幕的一部分,就可以获得一些性能。

    我在找类似的东西 renderInContext: withRect: UIGraphicsGetImageFromCurrentImageContextWithRect()

    仍然没有找到任何东西:(,如果你知道其他的选择,请帮助我。

    3 回复  |  直到 11 年前
        1
  •  6
  •   Felix    13 年前

    此方法使用较少的内存和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;
    }
    
        2
  •  0
  •   Rudiger    15 年前

    您可以先尝试光栅化UIView:

    view.layer.shouldRasterize = YES;
    

    我使用它的成功有限,但我是说我和你做了同样的事情(加上上面的一行),它工作得很好。你在什么情况下这样做?这可能是你的表现问题。

        3
  •  0
  •   M.Othman    10 年前

    迅捷版@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
    }
    
    推荐文章