美文网首页
iOS 将text文本转为image

iOS 将text文本转为image

作者: 拿铁加冰 | 来源:发表于2017-03-27 16:23 被阅读247次
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 100, 100)];
    imageView.backgroundColor = [UIColor cyanColor];
    imageView.layer.cornerRadius = 50;
    [self.view addSubview:imageView];
    
    UILabel *temptext = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    temptext.text = @"你好帅";
    temptext.textColor = [UIColor yellowColor];
    temptext.textAlignment = 1;
    UIImage *image = [self imageForView:temptext];
    imageView.image = image;
    
}

//-(UIImage *)imageFromString:(NSString *)string attributes:(NSDictionary *)attributes size:(CGSize)size{
//    
//    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
//    [string drawInRect:CGRectMake(0, 0, size.width, size.height) withAttributes:attributes];
//    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    
//    return image;
//    
//}

-(UIImage *)imageForView:(UIView *)view{
    
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0);
    
    if ([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
        
        [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    }else{
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

相关文章

网友评论

      本文标题: iOS 将text文本转为image

      本文链接:https://www.haomeiwen.com/subject/hypfottx.html