【问题标题】:How to render UIView into a CGContext如何将 UIView 渲染成 CGContext
【发布时间】:2011-02-18 12:41:31
【问题描述】:

我想将 UIView 渲染成 CGContextRef

-(void)methodName:(CGContextRef)ctx {
    UIView *someView = [[UIView alloc] init];

    MagicalFunction(ctx, someView);
}

所以,这里的 MagicalFunction 应该将 UIView(可能是它的层)渲染到当前上下文中。

我该怎么做?

提前致谢!

【问题讨论】:

    标签: iphone ipad ios uiview cgcontext


    【解决方案1】:

    CALayer的renderInContext方法怎么样?

    -(void)methodName:(CGContextRef)ctx {
        UIView *someView = [[UIView alloc] init];
        [someView.layer renderInContext:ctx];
    }
    

    编辑: 如评论中所述,由于过程中涉及的两个坐标系的原点不同,图层将被颠倒渲染。作为补偿,您只需要垂直翻转上下文。这在技术上是通过比例和平移变换完成的,可以组合成一个矩阵变换:

    -(void)methodName:(CGContextRef)ctx {
        UIView *someView = [[UIView alloc] init];
        CGAffineTransform verticalFlip = CGAffineTransformMake(1, 0, 0, -1, 0, someView.frame.size.height);
        CGContextConcatCTM(ctx, verticalFlip);
        [someView.layer renderInContext:ctx];
    }
    

    【讨论】:

    • 感谢工作!但是视图被颠倒了!有什么建议吗?
    • 你知道如何在 someView.layer 被渲染之前移动它吗?例如,我有一个长视图,我需要分成几页,所以我需要在将视图渲染到第二页之前调整我的视图。
    • @PsychoDad,这个方法独立于drawRect。如果您已覆盖 drawRect 以在视图中进行一些自定义绘图,它将按原样呈现到上下文中。
    猜你喜欢
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 2020-08-26
    • 2013-11-07
    • 2016-05-28
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    相关资源
    最近更新 更多