1.图片等比压缩
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
// 创建一个bitmap的context
// 并把它设置成为当前正在使用的context
UIGraphicsBeginImageContext(size);
// 绘制改变大小的图片
[img drawInRect:CGRectMake(0,0, size.width, size.height)];
// 从当前context中创建一个改变大小后的图片
UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
//返回新的改变大小后的图片
return scaledImage;
}
2.图片大小压缩
+(NSData *)imageData:(UIImage *)myimage{
NSData *data=UIImageJPEGRepresentation(myimage, 1.0);
if (data.length>100*1024) {
data = UIImageJPEGRepresentation(myimage, data.length/(300.0*1024));
}
return data;
}
3.图像截取
CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
UIGraphicsBeginImageContext(smallBounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, smallBounds, subImageRef);
UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
UIGraphicsEndImageContext();
return smallImage;
4.通过CGContext截取图片
- (void)drawRect:(CGRect)rect{
//画三角形,以便以后指定可以显示图片的范围
//获取图形上下文
CGContextRef ctx=UIGraphicsGetCurrentContext();
//CGContextAddEllipseInRect(ctx, CGRectMake(100, 100, 50, 50));
CGContextMoveToPoint(ctx, 100, 100);
CGContextAddLineToPoint(ctx, 60, 150);
CGContextAddLineToPoint(ctx, 140, 150);
CGContextClosePath(ctx);
//注意:指定范围(也就是指定剪切的方法一定要在绘制范围之前进行调用)
//指定上下文中可以显示内容的范围就是圆的范围
CGContextClip(ctx);
UIImage *image2=[UIImage imageNamed:@"me"];
[image2 drawAtPoint:CGPointMake(100, 100)];
}