简体   繁体   中英

How to draw attributedString in BezierPath to an image?

I'm using TextKit to get something like the following example (first image): a text (attributedString) placed into an area defined by using BezierPath as set as ExclusionPaths to NSTextContainer. The orange area is the excluded area, so the text will only be drawn into the blue area.

显示文字

So far so good. My question is, how can I draw the text to an image as shown? So I have an image with a transparent background and text only, like this:

只有文字的透明图像

Has anyone an idea how to achieve this?

It looks like you are trying to implement an editor where users can enter text and then generate a final image. If that's the case, you can have the text view draw directly into your graphics context by finding the layer with text and having it draw onto your current context:

[layerWithText drawInContext:UIGraphicsGetCurrentContext()];

Through experimentation, I found that layerWithText == textView.layer.sublayers[0] on iOS8. Since you're in private space though, you cannot guarantee that configuration between iOS versions. A slightly better version would be the following, though it assumes the layer and all sublayers are at the same position with no transformations. My recommendation would be to just watch that nothing breaks when new versions come out.

- (void)drawLayer:(CALayer *)layer recursivelyInContext:(CGContextRef)context
{
    [layer drawInContext:context];
    for (CALayer *sublayer in layer.sublayers) {
        [self drawLayer:sublayer recursivelyInContext:context];
    }
}

This will of capture the background of the text view if not transparent, so you may want to do the following if that is the case:

UIColor *originalBackgroundColor = textView.backgroundColor;
textView.backgroundColor = [UIColor clearColor];
[self renderLayer:textView.layer recursivelyInContext:UIGraphicsGetCurrentContext()];
textView.backgroundColor = originalBackgroundColor;

Example project: https://github.com/bnickel/SO25148857

Note: I had originally suggested renderInContext: as this renders the view's layer and all sublayers. This unfortunately appears to present a cached rasterization of the layer hierarchy. drawInContext: in contrast renders a single layer but forces a fresh drawing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM