【问题标题】:Rendering UIView with its children渲染 UIView 及其子项
【发布时间】:2009-04-25 10:29:14
【问题描述】:

我有一个UIView,它有一个图像和一些按钮作为它的子视图。我想使用renderInContext 或其他方法获取它的“快照”图像。

[clefView.layer renderInContext:mainViewContentContext];

如果我将UIView(如上)传递给它,那么我会得到一个空白位图。没有孩子被渲染到位图中。

如果我将作为图像的子视图传递给它,那么我会得到该位图的图像,并且不出所料,没有它的兄弟(按钮)。

我有点希望renderInContext 会获取图像及其所有可见的子元素并将其渲染为位图。有没有人知道如何做到这一点?

【问题讨论】:

    标签: iphone uiview rendering


    【解决方案1】:

    试试这样的:

    UIGraphicsBeginImageContext(clefView.bounds.size);
    [clefView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    【讨论】:

    • 谢谢,但没有这样做。我得到相同的结果。我认为,问题在于 renderInContext 没有遍历子视图,而只执行传递给它的顶层(尽管我认为它应该这样做)。我必须为每个子视图调用 renderInContext 吗?
    • 好的,多玩一点,这是正确的答案。我的 ImageContext 被设置为兄弟视图而不是超级视图。谢谢!
    • 这比我遇到的任何其他方法都好用。
    • #import <QuartzCore/QuartzCore.h> 避免警告
    • 找了很久的解决办法。您找到的解决方案是否有任何提示?
    【解决方案2】:

    简单的 4 行版本不适合我。我有一个 UIView(带有子层)和一个子 UITextView。我可以将 UIView 渲染到 UIImage 中,但是子 UITextView 没有被渲染。

    我的简单解决方法如下:

    CGRect rect = [view bounds];
    UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    [view.layer renderInContext:context];
    for (UIView *sv in view.subviews)
    {
        CGContextTranslateCTM(context, sv.frame.origin.x, sv.frame.origin.y);
        [sv.layer renderInContext:context];
        CGContextTranslateCTM(context, -sv.frame.origin.x, -sv.frame.origin.y);
    }
    
    UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    请注意,CGContextTranslateCTM 的简单使用假设子视图除了平移之外没有任何变换。另外我假设子视图完全包含在父视图框架中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      相关资源
      最近更新 更多