UIImage 图片处理
1.等比率缩放
1 //等比率缩放 2 - (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize { 3 //设置图片的上下文 4 UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize, image.size.height*scaleSize)); 5 //绘制图片的大小 6 [image drawInRect:CGRectMake(0, 0, image.size.width*scaleSize, image.size.height*scaleSize)]; 7 //生成新的图片 8 UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); 9 //结束上下文的编辑 10 UIGraphicsEndImageContext(); 11 //返回图片 12 return scaledImage; 13 }
2.自定义宽高
1 //自定长宽 2 - (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize { 3 //设置上下文 4 UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height)); 5 //重定义大小 6 [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)]; 7 //生成新图片 8 UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext(); 9 //结束上下文 10 UIGraphicsEndImageContext(); 11 //返回图片 12 return reSizeImage; 13 }
3.处理某个特定的view
1 //处理某个特定的view 2 - (UIImage *)captureView:(UIView *)theView { 3 //取得当前view的frame 4 CGRect rect = theView.frame; 5 //开始上下文 6 UIGraphicsBeginImageContext(rect.size); 7 // 8 CGContextRef context = UIGraphicsGetCurrentContext(); 9 // 10 [theView.layer renderInContext:context]; 11 //将view转换为图片 12 UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); 13 //结束上下文 14 UIGraphicsEndImageContext(); 15 //返回图片 16 return img; 17 }
其中,在view里面实现
1 UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; 2 imageView.image = [UIImage imageNamed:@"1.jpg"]; 3 [self addSubview:imageView];
4.存储图片,存到app的文件里
1 - (void)saveImage:(UIImage *)image image:(int)location{ 2 if (location == 1) { 3 //存储路径,以及存储的文件名字 4 NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"xiaoye.png"]; 5 //将图片写入文件 6 [UIImagePNGRepresentation(image) writeToFile:path atomically:YES]; 7 //找到Documents文件目录 8 NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 9 //输出Documents目录下得文件名字 10 NSLog(@"存储到docments目录下的文件有:%@",[[NSFileManager defaultManager] subpathsAtPath:docPath]); 11 } 12 }
5.在viewdidload里测试
1 UIImage *image = [UIImage imageNamed:@"1.jpg"]; 2 3 //等比率的缩放 4 UIImage *scaledImage = [self scaleImage:image toScale:0.5f]; 5 NSLog(@"%@",scaledImage); 6 7 //自定长宽 8 UIImage *reSizeImage = [self reSizeImage:image toSize:CGSizeMake(100.0f, 50.0f)]; 9 NSLog(@"%@",reSizeImage); 10 11 //处理特定的view,继承自uiview,需要导入QuzrtzCore.framework 12 MyView *view = [[MyView alloc] initWithFrame:CGRectMake(0, 0, 160, 240)]; 13 UIImage *img = [self captureView:view]; 14 NSLog(@"%@",img); 15 16 //存储图片到Documents目录下 17 [self saveImage:image image:1]; 18 19 //测试图片,scaledImage,reSizeImage,img 20 self.view.backgroundColor = [UIColor colorWithPatternImage:img];