3


我正在寻找在 UITextView 中
为 UILabel 中的文本添加轮廓/笔划的解决方案,我可以通过覆盖轻松地做到这一点- (void)drawTextInRect:(CGRect)rect
我还找到了一些解决方案,但它们对我不起作用:
- 对于 iOS 7,我发现了这个可以通过使用NSString方法解决:drawInRect:rect withAttributes:像这样

- (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];
}

iOS <7 是否可以支持任何解决方案?谢谢

4

1 回答 1

2

我为也在寻找这个问题的人更新了答案。
子类 UITextView 并像这样覆盖 drawRect 函数

- (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);
}
于 2013-10-09T03:40:09.677 回答