2010-10-12 43 views
8

Tôi đang cố gắng cắt một vùng của một UIView, thành một UIImage để sử dụng lại sau này.UIImage từ một khu vực của UIView

Tôi đã làm việc ra mã này từ một số đoạn:

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

'xem' là UIView mà tôi cắt và _finalImageUIImage tôi muốn.

Mã hoạt động không có vấn đề, tuy nhiên là loại chậm. Tôi tin rằng một số hiệu suất có thể đạt được bằng cách chỉ lấy phần màn hình trực tiếp trong Bước A.

Tôi đang tìm một cái gì đó như renderInContext: withRect: hoặc UIGraphicsGetImageFromCurrentImageContextWithRect() hehe.

Vẫn chưa tìm thấy bất cứ điều gì chưa :(, xin vui lòng giúp đỡ tôi nếu bạn biết một số thay thế

+0

bạn có thể định dạng lại không? khó đọc – Rudiger

Trả lời

6

Phương pháp này clip một vùng quan điểm sử dụng ít bộ nhớ và CPU thời gian:

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

Bạn có thể thử rasterizing các UIView đầu tiên:.

view.layer.shouldRasterize = YES; 

tôi đã hạn chế thành công sử dụng này, nhưng là nói rằng tôi đang làm điều tương tự như bạn (cộng với dòng trên) và nó hoạt động tốt.Trong bối cảnh bạn đang làm điều này? Nó có thể là vấn đề hiệu suất của bạn. các giới hạn của chế độ xem thay vì khung của chế độ xem. không phải lúc nào cũng giống nhau.

+0

Ngữ cảnh 'chính' tôi nghĩ. Tôi tạo ra một bối cảnh mới trên chủ đề chính. :S – almosnow

0

phiên bản Swift của @ phix23 giải pháp. thêm quy mô

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 
} 
Các vấn đề liên quan