1)用下面的代码写一个带有文本的图像
UIImage *textedImage = [self imageFromText:@"Text to show"];
-(UIImage *)imageFromText:(NSString *)text
{
//set width for string to wrap.
CGSize maximumSize;
maximumSize = CGSizeMake(320, 300);
//set your text image font here
UIFont *font = [UIFont boldSystemFontOfSize:50];
CGSize strSize1 = [text sizeWithFont:font constrainedToSize:maximumSize lineBreakMode:UILineBreakModeWordWrap];
CGSize strSize =CGSizeMake(320, strSize1.height);
if (UIGraphicsBeginImageContextWithOptions != NULL)
UIGraphicsBeginImageContextWithOptions(strSize,NO,0.0);
else
UIGraphicsBeginImageContext(strSize);
//set your new text iamge frame here
CGRect newframe = CGRectMake(0, 0, 320, 400);
UIColor *color = [UIColor redColor];
[color set];
[text drawInRect:newframe
withFont:font
lineBreakMode:UILineBreakModeCharacterWrap
alignment:UITextAlignmentCenter];
UIImage *textImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return textImg;
}
2)获得纹理图像后,应用所需图像的图像制作
UIImage *maskedImage = [self maskImage:finalImage withMask: textedImage];
- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//UIImage *maskImage = [UIImage imageNamed:@"mask.png"];
CGImageRef maskImageRef = [maskImage CGImage];
// create a bitmap graphics context the size of the image
CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
if (mainViewContentContext==NULL)
return NULL;
CGFloat ratio = 0;
ratio = maskImage.size.width/ image.size.width;
if(ratio * image.size.height < maskImage.size.height) {
ratio = maskImage.size.height/ image.size.height;
}
CGRect rect1 = {{0, 0}, {maskImage.size.width, maskImage.size.height}};
CGRect rect2 = {{-((image.size.width*ratio)-maskImage.size.width)/2 , -((image.size.height*ratio)-maskImage.size.height)/2}, {image.size.width*ratio, image.size.height*ratio}};
CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);
// Create CGImageRef of the main view bitmap content, and then
// release that bitmap context
CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
CGContextRelease(mainViewContentContext);
UIImage *theImage = [UIImage imageWithCGImage:newImage];
CGImageRelease(newImage);
// return the image
return theImage;
}