如何在iOS上使用文本来绘制图像?

我想绘制文字就像下面的样式 – 图像总是在右上angular,文字是在图像周围。

在这里输入图像说明

任何人都可以告诉我如何在iOS上实现这个? 我需要使用核心文本吗?

提前致谢!

是的,CoreText是这样做的最好方法。 在这里发布的代码有点长。 一些代码可能会指向正确的方向是文章“剪切到CGPath的CGRect”。 如果这样做的过程仍然令人困惑的话,那么我就可以写下我一直在写这个主题的博客文章。

第1步:创build一个从UIViewinheritance的对象

第2步:重写 – (void)drawRect:(CGRect)rect方法

第3步:将下面的代码添加到此方法

/* Define some defaults */ float padding = 10.0f; /* Get the graphics context for drawing */ CGContextRef ctx = UIGraphicsGetCurrentContext(); /* Core Text Coordinate System is OSX style */ CGContextSetTextMatrix(ctx, CGAffineTransformIdentity); CGContextTranslateCTM(ctx, 0, self.bounds.size.height); CGContextScaleCTM(ctx, 1.0, -1.0); CGRect textRect = CGRectMake(padding, padding, self.frame.size.width - padding*2, self.frame.size.height - padding*2); /* Create a path to draw in and add our text path */ CGMutablePathRef pathToRenderIn = CGPathCreateMutable(); CGPathAddRect(pathToRenderIn, NULL, textRect); /* Add a image path to clip around, region where you want to place image */ CGRect clipRect = CGRectMake(padding, self.frame.size.height-50, 50, 40); CGPathAddRect(pathToRenderIn, NULL, clipRect); /* Build up an attributed string with the correct font */ NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:self.Text]; //setFont CTFontRef font = CTFontCreateWithName((CFStringRef) [UIFont systemFontOfSize:10].fontName, [UIFont systemFontOfSize:10].lineHeight, NULL); CFAttributedStringSetAttribute(( CFMutableAttributedStringRef) attrString, CFRangeMake(0, attrString.length), kCTFontAttributeName,font); //set text color CGColorRef _white=[UIColor whiteColor].CGColor; CFAttributedStringSetAttribute(( CFMutableAttributedStringRef)(attrString), CFRangeMake(0, attrString.length),kCTForegroundColorAttributeName, _white); /* Get a framesetter to draw the actual text */ CTFramesetterRef fs = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef) attrString); CTFrameRef frame = CTFramesetterCreateFrame(fs, CFRangeMake(0, attrString.length), pathToRenderIn, NULL); /* Draw the text */ CTFrameDraw(frame, ctx); /* Release the stuff we used */ CFRelease(frame); CFRelease(pathToRenderIn); CFRelease(fs); 

第四步:使用如下:

 TextLayoutView *TextWrappingImage=[[TextLayoutView alloc] init...your own constructor...]; TextWrappingImage.backgroundColor=[UIColor clearColor]; [cell addSubview:TextWrappingImage]; //Add as subview where you want 

类似的问题。 我通过使用标准标记标记在HTML中创build带有文本的graphics文档来解决此问题,将html和png添加到我的项目中,并使用UIWebView显示它。 🙂