Drawing colored text in UIView's -drawRect: method

后端 未结 2 1048
天涯浪人
天涯浪人 2021-02-06 23:42

I am trying to draw colored text in my UIView subclass. Right now I am using the Single View app template (for testing). There are no modifications except the

相关标签:
2条回答
  • 2021-02-07 00:20

    Instead of UITextAttributeTextColor you should use NSForegroundColorAttributeName. Hope this helps!

    0 讨论(0)
  • 2021-02-07 00:28

    You can try with following methods. It will help you to draw text in UIView at the bottom right corner with the help of following attributes.

    • NSFontAttributeName - Font name with size
    • NSStrokeWidthAttributeName - Stroke Width
    • NSStrokeColorAttributeName - Text Color

    Objective-C - Draw text in the UIView and return as 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 - Draw text in the UIView and return as 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;
        }`
    
    0 讨论(0)
提交回复
热议问题