2011-03-12 31 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