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

时间:2011-03-12 18:28:32

标签: objective-c ios uitableview nsstring core-text

我想像下面的样式一样绘制文本 - 图像始终位于右上角,文本位于图像周围。

enter image description here

有谁能告诉我如何在iOS上实现这一点?我需要使用核心文本吗?

提前致谢!

3 个答案:

答案 0 :(得分:12)

是的,CoreText是执行此操作的最佳方式。这样做的代码有点长。一些可能指向正确方向的代码在文章"Clipping a CGRect to a CGPath."中如果执行它的过程仍然令人困惑,请ping我,我最后写了一篇博文,我一直想写这个主题。< / p>

答案 1 :(得分:1)

步骤1:创建从UIView继承的对象

第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);

步骤4:使用如下;

TextLayoutView *TextWrappingImage=[[TextLayoutView alloc] init...your own constructor...];

 TextWrappingImage.backgroundColor=[UIColor clearColor];

 [cell addSubview:TextWrappingImage]; //Add as subview where you want

答案 2 :(得分:0)

类似的问题。我通过使用标准标记标记在HTML中创建带文本图形文档,将html和pngs添加到我的项目中,并使用UIWebView显示它来解决它。 : - )