在iOS <7中为UITextView添加轮廓/描边效果

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以下版本的解决方案?谢谢。

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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接