如何从零开始创建UIImage。具体来说,我想创建一个大小为320x50的UIImage。然后,我想能够在该图像上绘制特定颜色的多边形。
这里有一个答案:如何在iPhone上拼接图片
根据我的经验,我可以给你一些注意事项:
等比例缩放
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize { UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize)); [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)]; UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; }
调整大小
- (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize { UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height)); [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)]; UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return reSizeImage; }
处理特定视图
首先要导入QuzrtzCore.framework
-(UIImage*)captureView:(UIView *)theView { CGRect rect = theView.frame; UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); [theView.layer renderInContext:context]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; }
处理图片范围
CGRect captureRect = yourRect; CGRect viewRect = self.view.frame; UIImage *viewImg; UIImage *captureImg;
UIGraphicsBeginImageContext(viewRect.size); CGContextRef context = UIGraphicsGetCurrentContext(); [self.view.layer renderInContext:context]; viewImg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
captureImg = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(viewImg.CGImage, captureRect)];
保存图片
保存在应用程序中
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"image.png"]; [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
保存在相册中
CGImageRef screen = UIGetScreenImage(); UIImage* image = [UIImage imageWithCGImage:screen]; CGImageRelease(screen); UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
我在这里留下我的答案,以防将来有所帮助。这个答案适用于iOS10及以上版本。
extension UIImage {
static func image(with size: CGSize) -> UIImage {
UIGraphicsImageRenderer(size: size)
.image { $0.fill(CGRect(origin: .zero, size: size)) }
}
}
所以你可以这样做:
UIImage.image(with: CGSize(width: 320, height: 50))
我的答案受到以下内容的启发:https://dev59.com/fF8d5IYBdhLWcg3wsT4b#48441178
CGBitmapContext
。CGBitmapContextCreateImage
的结果创建UIImage
。