iOS 圖片上繪制文字


- (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],NSForegroundColorAttributeName:[UIColor whiteColor]}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;

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM