簡體   English   中英

需要將UIView捕獲到UIImage中,包括所有子視圖

[英]Need to capture UIView into a UIImage, including all subviews

我需要將UIView及其所有子視圖捕獲到UIImage中。 問題是部分視圖在屏幕外,所以我無法使用屏幕捕獲功能,當我嘗試使用UIGraphicsGetImageFromCurrentImageContext()函數時,它似乎也不會捕獲子視圖。 它應該捕獲子視圖,我只是做錯了嗎? 如果沒有,還有其他方法可以實現嗎?

這是正確的方法:

+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, [[UIScreen mainScreen] scale]); 
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

這種方法是UIImage類的擴展方法,它還可以在任何未來的高分辨率設備上使圖像看起來很好。

你的意思是

UIGraphicsBeginImageContext(view.bounds.size);
[view.layer drawInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

不起作用? 我很確定它應該......

Swift 4+版本:

func getImage(from view:UIView) -> UIImage? {

    defer { UIGraphicsEndImageContext() }
    UIGraphicsBeginImageContextWithOptions(view.frame.size, true, UIScreen.main.scale)
    guard let context =  UIGraphicsGetCurrentContext() else { return nil }
    view.layer.render(in: context)
    return UIGraphicsGetImageFromCurrentImageContext()   

}

這是一個Swift 2.x版本,如果你首先創建一個UIViews數組來展平,它應該可以工作:

// Flattens <allViews> into single UIImage
func flattenViews(allViews: [UIView]) -> UIImage? {
    // Return nil if <allViews> empty
    if (allViews.isEmpty) {
        return nil
    }

    // If here, compose image out of views in <allViews>
    // Create graphics context
    UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, UIScreen.mainScreen().scale)
    let context = UIGraphicsGetCurrentContext()
    CGContextSetInterpolationQuality(context, CGInterpolationQuality.High)

    // Draw each view into context
    for curView in allViews {
        curView.drawViewHierarchyInRect(curView.frame, afterScreenUpdates: false)
    }

    // Extract image & end context
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    // Return image
    return image
}

暫無
暫無

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

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