24

我正在尝试在我的UIView子类中绘制彩色文本。现在我正在使用单视图应用程序模板(用于测试)。除了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 : 字体, NSForegroundColorAttributeName : textColor };

4

2 回答 2

22

而不是UITextAttributeTextColor你应该使用NSForegroundColorAttributeName. 希望这可以帮助!

于 2012-12-15T17:18:03.087 回答
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;
    }`
于 2016-02-11T08:38:55.043 回答