swift中把UIImage中添加UILabel后生成新的UIImage:
func drawCornerHeaderImage(headerCharArr:[String]) -> UIImage { print("drawCornerHeaderImage:") print("headerCharArr.count=\(headerCharArr.count)") print("headerCharArr=\(headerCharArr)") var rectHeaderImage:UIImage var cornerHeaderImageArr:[UIImage] = Array() var mergedCornerHeaderImage:UIImage = UIImage() let headImageSize:CGFloat switch headerCharArr.count { case 1: headImageSize = SIZE_CONVERSATION_HEADER_1 case 3: headImageSize = SIZE_CONVERSATION_HEADER_3 case 4: headImageSize = SIZE_CONVERSATION_HEADER_4 case 9: headImageSize = SIZE_CONVERSATION_HEADER_9 default: headImageSize = 0 break } for (index, singleHeaderChar) in headerCharArr.enumerate() { print("singleHeaderChar=\(singleHeaderChar)") let headerLabel:UILabel headerLabel = UILabel(frame: CGRectMake( 0, 0, headImageSize, headImageSize)) headerLabel.font = FONT_CONVERSATION_HEADER headerLabel.textColor = UIColor.whiteColor() headerLabel.text = singleHeaderChar headerLabel.textAlignment = NSTextAlignment.Center headerLabel.backgroundColor = UIColor.clearColor() rectHeaderImage = drawRectangleImage( CGSizeMake(headImageSize, headImageSize), color: getRandomHeaderColor()) cornerHeaderImageArr[index] = drawCornerImage(rectHeaderImage, cornerRadius: 4) cornerHeaderImage.add .addSubview(headerLabel) }
注:
此处由于不方便用UIImageView,所以就只是需要
把label合并到UIImage中。
搜:
swift UIImage add UILabel
参考:
搜:
swift merge UILabel into UIImage
参考:
把简字的label,放入到UIImage中:
//draw a rectangle image, filled with color, with size, with label func drawRectangleImageWithLabel(size:CGSize, color:UIColor, label:UILabel) -> UIImage { let opaque:Bool = false let scale:CGFloat = 0 UIGraphicsBeginImageContextWithOptions(size, opaque, scale) let context = UIGraphicsGetCurrentContext() //CGContextSetLineWidth(context, 4.0) //CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor) let rectangle = CGRectMake(0, 0, size.width, size.height) CGContextAddRect(context, rectangle) CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillRect(context, rectangle) //label.drawTextInRect(rectangle) label.layer.renderInContext(context!) // Drawing complete, retrieve the finished image and cleanup let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } let headerLabel:UILabel headerLabel = UILabel(frame: CGRectMake( 0, 0, headImageSize, headImageSize)) headerLabel.font = FONT_CONVERSATION_HEADER headerLabel.textColor = UIColor.whiteColor() headerLabel.text = "简" headerLabel.textAlignment = NSTextAlignment.Center headerLabel.backgroundColor = UIColor.clearColor() rectHeaderImage = drawRectangleImageWithLabel( CGSizeMake(headImageSize, headImageSize), color: getRandomHeaderColor(), label: headerLabel)
效果:
更多的图片相关的函数,可参考: