美文网首页
获得一个绘制有文字的图片

获得一个绘制有文字的图片

作者: 傅里叶的幻想 | 来源:发表于2017-04-24 19:13 被阅读0次
    - (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize
    {
        //画布大小
        CGSize size=CGSizeMake(self.size.width,self.size.height);
        //创建一个基于位图的上下文
        UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO  scale:0.0
     
        [self drawAtPoint:CGPointMake(0.0,0.0)];
     
        //文字居中显示在画布上
        NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
        paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
        paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中
     
        //计算文字所占的size,文字居中显示在画布上
        CGSize sizeText=[title boundingRectWithSize:self.size options:NSStringDrawingUsesLineFragmentOrigin
                                         attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size;
        CGFloat width = self.size.width;
        CGFloat height = self.size.height;
     
        CGRect rect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height);
        //绘制文字
        [title drawInRect:rect withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}];
     
        //返回绘制的新图形
        UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
    }
    

    相关文章

      网友评论

          本文标题:获得一个绘制有文字的图片

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