1. 程式人生 > >IOS UILabel 文字描邊詳解

IOS UILabel 文字描邊詳解

剛開始覺得這功能很娛樂…… 後來想想,任何設計都是有他的道理,有他的原因的,除非特別不合理,我會選擇無視。 無論美醜,人家設計出來,作為RD,你就應該能夠夠給做出來(值不值得做 另說),就算沒幾天被砍掉,也沒轍…… 最開始實在這裡找到的答案: http://stackoverflow.com/questions/1103148/how-do-i-make-uilabel-display-outlined-text 看完之後覺得好簡單…… 如果你只是簡單的想加個描邊,而不需要為以後做更好的擴充套件,或者做成公共的Custom Label控制元件,下面的程式碼足夠你了。
- (void)drawTextInRect:(CGRect)rect {

  CGSize shadowOffset = self.shadowOffset;
  UIColor *textColor = self.textColor;

  CGContextRef c = UIGraphicsGetCurrentContext();
  CGContextSetLineWidth(c, 1);
  CGContextSetLineJoin(c, kCGLineJoinRound);

  CGContextSetTextDrawingMode(c, kCGTextStroke);
  self.textColor = [UIColor whiteColor];
  [super drawTextInRect:rect];

  CGContextSetTextDrawingMode(c, kCGTextFill);
  self.textColor = textColor;
  self.shadowOffset = CGSizeMake(0, 0);
  [super drawTextInRect:rect];

  self.shadowOffset = shadowOffset;

}
當然,如果你有更高的追求,更好的封裝意識…… 用這個:https://github.com/vigorouscoding/KSLabel。 還有這個:https://github.com/MuscleRumble/THLabel 都是很好的Demo。
參考:https://developer.apple.com/library/mac/documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_text/dq_text.html#//apple_ref/doc/uid/TP30001066-CH213-TPXREF101

Text drawing modes

Use this mode

When you want to . . .

Example

Perform a fill operation on the text.

Filled text

Perform a stroke operation on the text.

Stroked text.

Perform both fill and stroke operations on the text.

Filled and stroked test.

Get text positions for the purpose of measuring text but not display the text. Note that the text position (x

y) is updated, as with all of the drawing modes.

Invisible text.

Perform a fill operation, then add the text to the clipping area.

Filled text added to the clipping area.

Perform a stroke operation, then add the text to the clipping area.

Stroked text, added to the clipping area

Perform both fill and stroke operations, then add the text to the clipping area.

Filled and stroked text, aded to the clipping area

Add the text to the clipping area, but do not draw the text.

Test added to the clipping area, but not drawn