CGImageCreateWithImageInRect图片裁剪问题
2016-06-23 11:07
681 查看
当我们直接使用CGImageCreateWithImageInRect获取图片时,会发现我们实际得到的截取图像,恰好是当rect旋转90°时,应该得到的图像:
这是因为CGImageCreateWithImageInRect中得rect是获取自UIImage中得rect,而不是UIImageView的;而在UIImage的坐标系中,(0,0)点位于左下角,因此在裁剪区域确定时,需要转换成对应坐标系中得区域:以下是转换代码:
参考链接:CGImageCreateWithImageInRect not Cropping Correctly
- (UIImage *)cropImage:(UIImage*)image toRect:(CGRect)rect { CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage,rect); UIImage *result = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation]; return result;
这是因为CGImageCreateWithImageInRect中得rect是获取自UIImage中得rect,而不是UIImageView的;而在UIImage的坐标系中,(0,0)点位于左下角,因此在裁剪区域确定时,需要转换成对应坐标系中得区域:以下是转换代码:
- (UIImage *)cropImage:(UIImage*)image toRect:(CGRect)rect { CGFloat (^rad)(CGFloat) = ^CGFloat(CGFloat deg) { return deg / 180.0f * (CGFloat) M_PI; }; // determine the orientation of the image and apply a transformation to the crop rectangle to shift it to the correct position CGAffineTransform rectTransform; switch (image.imageOrientation) { case UIImageOrientationLeft: rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -image.size.height); break; case UIImageOrientationRight: rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -image.size.width, 0); break; case UIImageOrientationDown: rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -image.size.width, -image.size.height); break; default: rectTransform = CGAffineTransformIdentity; }; // adjust the transformation scale based on the image scale rectTransform = CGAffineTransformScale(rectTransform, image.scale, image.scale); // apply the transformation to the rect to create a new, shifted rect CGRect transformedCropSquare = CGRectApplyAffineTransform(rect, rectTransform); // use the rect to crop the image CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, transformedCropSquare); // create a new UIImage and set the scale and orientation appropriately UIImage *result = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation]; // memory cleanup CGImageRelease(imageRef); return result; }
参考链接:CGImageCreateWithImageInRect not Cropping Correctly
相关文章推荐
- iOS 手势滑动返回功能
- ios::sync_with_stdio(false);(读入优化)
- iOS TableView实现QQ好友列表
- iOS开发:字典(NSDictionary)和数组( NSArray)转换成字符串
- ios webView与js的交互
- OC获取folder下文件的路径
- iOS流媒体工程后台运行
- IOS 中的 _cmd 代表本方法的名称
- iOS 程序间跳转传参(支付和地图)
- cordova local notification sound not working in ios and andorid
- iOS小demo之判断数值类型
- iOS自动更新如何实现
- iOS 修改状态栏的颜色
- iOS-通过键盘的监听完成底部工具条的黏性移动
- iOS 核心动画Core Animation
- 如何用xcode7.3在ios10的真机上调试代码
- iOS开发之优秀开源框架IQKeyboardManager,零行代码解决键盘遮挡问题,如此简单解决键盘遮挡问题,IQKeyboardManager源码分解
- iOS App开发中Core Data框架基本的数据管理功能小结
- 《Motion Design for iOS》(二十六)
- iOS 加急审核的办法