美文网首页
iOS 字符串截取生成图片

iOS 字符串截取生成图片

作者: Tim王 | 来源:发表于2017-08-31 14:43 被阅读22次

    代码如下:

    #import@interface UIImage (mask)

    /**

    *  在一张背景图上绘制文字并且居中

    *

    *  @param str      要绘制到图片上的文字

    *  *

    *

    */

    + (UIImage *)createOtherMerchantImage:(NSString *)str  size:(CGSize)size;

    @end

    #import "UIImage+mask.h

    "@implementation UIImage (mask)

    + (UIImage *)createOtherMerchantImage:(NSString *)str  size:(CGSize)size{          NSString * substring = [str substringFromIndex:str.length-2];     

       int texthash = (int)[str hash];   

     texthash=abs(texthash)+1;   

     int lastNum=texthash%10;   

     if (lastNum>=5) {       

     lastNum=lastNum-5;  

      }       

     NSArray* colorArr=@[

    [UIColor colorWithRed:237/255.0f green:151/255.0f blue:151/255.0f alpha:1.0],

    [UIColor colorWithRed:237/255.0f green:197/255.0f blue:151/255.0f alpha:1.0],

    [UIColor colorWithRed:151/255.0f green:198/255.0f blue:237/255.0f alpha:1.0],

    [UIColor colorWithRed:145/255.0f green:224/255.0f blue:152/255.0f alpha:1.0],

    [UIColor colorWithRed:176/255.0f green:164/255.0f blue:162/255.0f alpha:1.0],

    ];

    NSDictionary * fontAttributes = @{

    NSFontAttributeName:[UIFont systemFontOfSize:15],//设置文字的字体

    NSForegroundColorAttributeName: [UIColor whiteColor]

    };

    CGSize textSize = [substring sizeWithAttributes:fontAttributes];

    CGPoint drawPoint = CGPointMake((size.width - textSize.width)/2, (size.height - textSize.height)/2);

    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);

    CGContextRef context = UIGraphicsGetCurrentContext();

    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];

    CGContextSetFillColorWithColor(context, colorArr[lastNum].CGColor);

    [path fill];

    [substring drawAtPoint:drawPoint withAttributes:fontAttributes];

    UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return resultImg;

    }

    @end

    相关文章

      网友评论

          本文标题:iOS 字符串截取生成图片

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