任何新的位图绘制代码是鼓励使用UIGraphicsImageRenderer leiu这个API
UIKIT_EXTERN void UIGraphicsBeginImageContext(CGSize size);
UIKIT_EXTERN void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) NS_AVAILABLE_IOS(4_0);
UIKIT_EXTERN UIImage* __nullable UIGraphicsGetImageFromCurrentImageContext(void);
UIKIT_EXTERN void UIGraphicsEndImageContext(void);
1.等比缩放
- (UIImage *) scaleImage:(UIImage *)image dengbiScale:(float)dengbiScale {
UIGraphicsBeginImageContext(CGSizeMake(image.size.width * dengbiScale, image.size.height * dengbiScale);
[image drawInRect:CGRectMake(0, 0, image.size.width * dengbiScale, image.size.height * dengbiScale)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
2.自定义大小
- (UIImage *) reSizeImage:(UIImage *)image scaletoSize:(CGSize)scaletoSize {
UIGraphicsBeginImageContext(CGSizeMake(scaletoSize.width, scaletoSize.height));
[image drawInRect:CGRectMake(0, 0, scaletoSize.width, scaletoSize.height)];
UIImage *mySizeImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return mySizeImage;
}
3.处理某个特定的View
-(UIImage*) captureView:(UIView *)tedingView {
CGRect rect = tedingView.frame;
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[tedingView.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
4.储存图片(存入到文件夹中)
NSString *path = [[NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"image.png"];
[UIImagePNGRepresentation(image) writeToFile:pathatomically:YES];
5.储存到手机的图片库中
CGImageRef screen = UIGetScreenImage();
UIImage* image = [UIImage imageWithCGImage:screen];
CGImageRelease(screen);
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
6.根据给定得图片,从其指定区域截取一张新得图片
-(UIImage *)getImageFromImage{
//大图bigImage
//定义myImageRect,截图的区域
CGRect myImageRect = CGRectMake(10.0, 10.0, 57.0, 57.0);
UIImage* bigImage= [UIImage imageNamed:@"k00030.jpg"];
CGImageRef imageRef = bigImage.CGImage;
CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, myImageRect);
CGSize size;
size.width = 57.0;
size.height = 57.0;
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, myImageRect, subImageRef);
UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
UIGraphicsEndImageContext();
return smallImage;
}
7. 合并两张图片
- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 {
UIGraphicsBeginImageContext(image1.size);
// Draw image1
[image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];
// Draw image2
[image2 drawInRect:CGRectMake(0, 0, image2.size.width, image2.size.height)];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultingImage;
}