在UIView -drawRect:方法中绘制彩色文本

时间:2012-12-15 16:54:24

标签: ios uikit drawrect uicolor nsattributedstring

我正在尝试在UIView子类中绘制彩色文本。现在我正在使用Single View应用程序模板(用于测试)。除drawRect:方法外,没有任何修改。

绘制文本但无论我将颜色设置为什么,它总是黑色的。

- (void)drawRect:(CGRect)rect
{
    UIFont* font = [UIFont fontWithName:@"Arial" size:72];
    UIColor* textColor = [UIColor redColor];
    NSDictionary* stringAttrs = @{ UITextAttributeFont : font, UITextAttributeTextColor : textColor };

    NSAttributedString* attrStr = [[NSAttributedString alloc] initWithString:@"Hello" attributes:stringAttrs];

    [attrStr drawAtPoint:CGPointMake(10.f, 10.f)];
}

我也试过[[UIColor redColor] set]无济于事。

答案:

  

NSDictionary * stringAttrs = @ {NSFontAttributeName:font,   NSForegroundColorAttributeName:textColor};

2 个答案:

答案 0 :(得分:22)

而不是UITextAttributeTextColor,您应该使用NSForegroundColorAttributeName。希望这有帮助!

答案 1 :(得分:4)

您可以尝试以下方法。它将帮助您在以下属性的帮助下在右下角的UIView中绘制文本。

  • NSFontAttributeName - 字体名称大小
  • NSStrokeWidthAttributeName - 笔触宽度
  • NSStrokeColorAttributeName - 文字颜色

Objective-C - 在UIView中绘制文本并返回UIImage。

    -(UIImage *) imageWithView:(UIView *)view text:(NSString *)text {

        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);

        [view.layer renderInContext:UIGraphicsGetCurrentContext()];

        // Setup the font specific variables
        NSDictionary *attributes = @{
                NSFontAttributeName   : [UIFont fontWithName:@"Helvetica" size:12],
                NSStrokeWidthAttributeName    : @(0), 
                NSStrokeColorAttributeName    : [UIColor blackColor]
        };
        // Draw text with CGPoint and attributes
        [text drawAtPoint:CGPointMake(view.frame.origin.x+10 , view.frame.size.height-25) withAttributes:attributes];

        UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return img;
    }`

Swift - 在UIView中绘制文字并返回UIImage。

    func imageWithView(view : UIView, text : NSString) -> UIImage {

        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
        view.layer.renderInContext(UIGraphicsGetCurrentContext()!);
        // Setup the font specific variables
        let attributes :[String:AnyObject] = [
            NSFontAttributeName : UIFont(name: "Helvetica", size: 12)!,
            NSStrokeWidthAttributeName : 0,
            NSForegroundColorAttributeName : UIColor.blackColor()
        ]
        // Draw text with CGPoint and attributes
        text.drawAtPoint(CGPointMake(view.frame.origin.x+10, view.frame.size.height-25), withAttributes: attributes);
        let img:UIImage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();
        return img;
    }`