6

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

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 = self.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)];
Mc.Lover
  • 4,813
  • 9
  • 46
  • 80
  • Why don't you try creating `label` in Interface Builder and making the connections so that your app does that absolute least amount of work? – Lynn Feb 23 '11 at 18:01
  • Thanks! Great idea! Still it needs to be parametrize, like the line width, color, etc. – Bogdan Jul 18 '12 at 16:23

2 Answers2

3

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.

donohoe
  • 13,867
  • 4
  • 37
  • 59
Leon
  • 31
  • 2
0

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

tobihagemann
  • 601
  • 8
  • 15