2011-03-12 189 views

回答

12

是的,CoreText是最好的方法。在这里发布的代码有点长。有些代码可能会指向您正确的方向"Clipping a CGRect to a CGPath."如果执行该过程仍然令人困惑,请ping我,然后我最终编写我一直有意写关于此主题的博文。

+0

我想我需要你的帮助。我不太了解您博客文章中的代码。你能写一篇关于这个话题的文章吗?谢谢! – nonamelive 2011-03-13 07:22:47

+0

还没有忘记这件事;它只是花了一点把它放在一起。 – 2011-03-25 15:42:21

+7

这有点粗糙,但希望它能让你朝着正确的方向前进。 http://robnapier.net/blog/wrapping-text-around-shape-with-coretext-540 – 2011-03-25 16:27:42

1

步骤1:创建从UIView的

继承对象步骤2:覆盖 - (无效)的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 
0

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

+0

+1。它可能不是最优雅的解决方案,但我使用这种方法,它是一行代码来处理这个问题,只是一些简单的CSS div元素。'width:95px;高度:95px; margin:5px 5px 5px 0px; border:1px solid #eee;向左飘浮;背景:url(%@)center center;背景重复:不重复; background-size:contains;'在我看来,更小更容易实现。谢谢 – thefoyer 2014-07-29 17:39:57