天天看點

UITextView轉UIImage

//TextView轉image

-(UIImage*) saveTextView

{

    //1.設定大小

    CGSize size  = _maskText.size;//

    _rect=_maskText.frame;

    if (UIGraphicsBeginImageContextWithOptions != NULL)

        UIGraphicsBeginImageContextWithOptions(size,NO,0);

    // draw in context, you can use  drawInRect/drawAtPoint:withFont:

    // 2.設定text屬性

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];

    paragraphStyle.alignment = NSTextAlignmentCenter;

    NSShadow *shadow=[[NSShadow alloc]init];

    shadow.shadowBlurRadius=2;//模糊度

    shadow.shadowColor=[UIColor blackColor];

    shadow.shadowOffset=CGSizeMake(1, 1);

    //設定文字屬性

    //此處具體設定根據個人情況添加,具體設定請看iOS- 詳解文本屬性Attributes 

    NSDictionary *dict=@{NSFontAttributeName:_maskText.font,NSForegroundColorAttributeName:[UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle,NSShadowAttributeName:shadow,NSVerticalGlyphFormAttributeName:@(0)};

    //NSStrokeColorAttributeName:[UIColor blackColor],NSStrokeWidthAttributeName:@0.5

    [_maskText.text drawInRect:CGRectMake(0, 0, size.width, size.height) withAttributes:dict];

    //3. 轉換為圖檔

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    _angle=0;

    return image;

}