Ios 为CoreText创建CGContext

Ios 为CoreText创建CGContext,ios,calayer,cgcontext,core-text,Ios,Calayer,Cgcontext,Core Text,我试图在CALayer中渲染一些CoreText,以便可以显式地调整该层的alpha。我尝试重写drawRect:方法,但据我所知,它只在视图的根层上绘制,我有两个子层,一个bg图像和CoreText。下面是尝试绘制CoreText层的方法:(如果删除createContext代码,它在drawRect中工作) --任何关于CALayers和CGContext的理论都非常受欢迎我可以提出三种不同的方法: 子类CALayer并实现其drawInContext: 将非ui视图的对象设置为子层的委托,

我试图在CALayer中渲染一些CoreText,以便可以显式地调整该层的alpha。我尝试重写drawRect:方法,但据我所知,它只在视图的根层上绘制,我有两个子层,一个bg图像和CoreText。下面是尝试绘制CoreText层的方法:(如果删除createContext代码,它在drawRect中工作)


--任何关于CALayers和CGContext的理论都非常受欢迎

我可以提出三种不同的方法:

  • 子类
    CALayer
    并实现其
    drawInContext:

  • 将非
    ui视图
    的对象设置为子层的
    委托
    ,然后实现
    drawLayer:inContext:

  • 创建
    CGImage
    并将其设置为图层内容:

    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    /// draw
    
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    sublayer.contents = (id)image.CGImage;
    
  • 我喜欢这个建议。关于前两个建议,drawInContext:method,它是将CALayer作为图像绘制到上下文中,还是使用param上下文绘制CALayer?
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    /// draw
    
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    sublayer.contents = (id)image.CGImage;