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

我想在我的UIView子类中绘制彩色的文字。 现在我正在使用Single View应用程序模板(用于testing)。 除了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};

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

你可以尝试下面的方法。 它将帮助你在右下angular的UIView中借助以下属性绘制文本。

  • NSFontAttributeName – 带大小的字体名称
  • NSStrokeWidthAttributeName – 描边宽度
  • NSStrokeColorAttributeName – 文本颜色

Objective-C – 在UIView中绘制文本并以UIImage的forms返回。

  -(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; }` 
    Interesting Posts