如何将UIView渲染到CGContext中

9

我想将一个UIView渲染到CGContextRef中

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

    MagicalFunction(ctx, someView);
}

所以,这里的MagicalFunction旨在将UIView(可能是其层)呈现到当前上下文中。
我该怎么做?
提前感谢!
1个回答

16

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];
}

谢谢,那个起作用了!但是视图被倒置了!有什么建议吗? - SPatil
你知道如何在视图渲染之前移动 someView.layer 吗?例如,我有一个很长的视图,需要将其分成几个页面,因此我需要在将其渲染到第二页之前调整我的视图。 - Slee
@PsychoDad,这个方法与drawRect无关。如果您已经重写了drawRect以在视图中进行一些自定义绘制,则它将按原样呈现到上下文中。 - Matt Wilding

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接