iOS 字符串截取生成圖片

代碼如下:

#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],//設(shè)置文字的字體

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容