Reputation: 1447
I'm looking for the solution to add outline/stroke to the text inside a UITextView
For UILabel, I can easily do this by override - (void)drawTextInRect:(CGRect)rect
I also found some solution but they didn't work for me:
- For iOS 7, I found this can be solved by using NSString
method: drawInRect:rect withAttributes:
like this
- (void)drawRect:(CGRect)rect
{
NSMutableDictionary *stringAttributes = [NSMutableDictionary dictionary];
// Define the font and fill color
[stringAttributes setObject: self.font forKey: NSFontAttributeName];
[stringAttributes setObject: self.textColor forKey: NSForegroundColorAttributeName];
// Supply a negative value for stroke width that is 2% of the font point size in thickness
[stringAttributes setObject: [NSNumber numberWithFloat: -2.0] forKey: NSStrokeWidthAttributeName];
[stringAttributes setObject: self.strokeColor forKey: NSStrokeColorAttributeName];
// Draw the string
[self.text drawInRect:rect withAttributes:stringAttributes];
}
Are there any solution that can be supported for iOS <7 ? Thanks
Upvotes: 3
Views: 3706
Reputation: 1447
I update the answer for someone also looking for this question.
Subclass UITextView and override the drawRect function like this
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGSize size = [self.text sizeWithFont:self.font constrainedToSize:rect.size lineBreakMode:NSLineBreakByWordWrapping];
CGRect textRect = CGRectMake((rect.size.width - size.width)/2,(rect.size.height - size.height)/2, size.width, size.height);
//for debug
NSLog(@"draw in rect: %@", NSStringFromCGRect(rect));
NSLog(@"content Size : %@", NSStringFromCGSize(self.contentSize));
NSLog(@"Text draw at :%@", NSStringFromCGRect(textRect));
CGContextRef textContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(textContext);
//set text draw mode and draw the stroke
CGContextSetLineWidth(textContext, 2); // set the stroke with as you wish
CGContextSetTextDrawingMode (textContext, kCGTextStroke);
CGContextSetStrokeColorWithColor(textContext, [UIColor blackColor].CGColor);
[self.text drawInRect:textRect withFont:self.font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter];
CGContextRestoreGState(textContext);
}
Upvotes: 2