开发者

uilabel with outline or stroke [duplicate]

This question already has answers here: How do I make UILabel display outlined text? (15 answers) Closed 8 years ago.

I was wondering how can I create text stroke for UILabel ? is there any possible way ?

uilabel with outline or stroke [duplicate]

thank you ,

#import <Foundation/Foundation.h>


@interface CustomLabel : UILabel {

 }

 @end

#import "CustomLabel.h"


@implementation CustomLabel

- (void)drawTextInRect:(CGRect)rect {

    CGSize shadowOffset = self.shadowOffset;
    UIColor *textColor = s开发者_Go百科elf.textColor;

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(c, 22);

    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;
    //works fine with no warning 
}   

now the question is how can i use this subclass with a IBOutlet label on different viewcontrollers . is it right :

    label = [[CustomLabel alloc] initWithFrame:CGRectMake(0, 0, 190, 190)];


It may be helpful to some to add that depending on font and characters, adding:

CGContextSetLineJoin(c,kCGLineJoinRound);

can prevent artifacts from too large a stroke applied to too sharp a character.


There is one issue with this implementation. Drawing a text with stroke has a slightly different character glyph width than drawing a text without stroke, which can produce "uncentered" results. You can fix that by adding an invisible stroke around the fill text.

You should replace:

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

with:

CGContextSetTextDrawingMode(context, kCGTextFillStroke);
self.textColor = textColor;
[[UIColor clearColor] setStroke]; // invisible stroke
self.shadowOffset = CGSizeMake(0, 0);
[super drawTextInRect:rect];

I'm not 100% sure, if that's the real deal, because I don't know if self.textColor = textColor; has the same effect as [textColor setFill], but you get the idea.

Disclosure: I'm the developer of THLabel.

I've released a UILabel subclass a while ago, which allows an outline in text and other effects. You can find it here: https://github.com/tobihagemann/THLabel

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜