将大纲/笔触效果添加到UITextView ios< 7

时间:2013-10-01 07:56:19

标签: iphone ios uilabel uitextview


我正在寻找在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 个答案:

答案 0 :(得分: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);
}