【发布时间】:2014-05-02 23:27:55
【问题描述】:
当尝试对 UIImage 进行中心裁剪时,我得到以下结果(左侧是640*1136 处的原始图像,右侧是在320*320 处适合正方形UIImageView 的裁剪图像):
转为:
我对比率元素进行了相当多的修改,以便它可以正确检测要修剪的数量:使用图像的较短边,基于short_side/width_of_desired_rect 构建比率,但它似乎不起作用在这种情况下。感谢您的帮助!
- (UIImage *)squareImageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
double ratio;
double delta;
CGPoint offset;
//make a new square size, that is the resized imaged width
CGSize sz = CGSizeMake(newSize.width, newSize.width);
//figure out if the picture is landscape or portrait, then
//calculate scale factor and offset
if (image.size.width > image.size.height) {
ratio = newSize.width / image.size.width;
delta = (ratio*image.size.width - ratio*image.size.height);
offset = CGPointMake(delta/2, 0);
} else {
ratio = newSize.width / image.size.height;
delta = (ratio*image.size.height - ratio*image.size.width);
offset = CGPointMake(0, delta/2);
}
//make the final clipping rect based on the calculated values
CGRect clipRect = CGRectMake(-offset.x, -offset.y,
(ratio * image.size.width) + delta,
(ratio * image.size.height) + delta);
//for retina consideration
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(sz, YES, 0.0);
} else {
UIGraphicsBeginImageContext(sz);
}
UIRectClip(clipRect);
[image drawInRect:clipRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
【问题讨论】:
-
仅供参考 - iOS 4.0 中添加了
UIScreen的scale属性。没有必要再检查它了。 -
你没有裁剪。您正在将整个图像重新绘制到一个较小的区域中。搜索“ios裁剪图片”,你会找到很多解决问题的方法。
-
谢谢@rmaddy - 我想我正在裁剪和重绘图像(压扁的图像有 8 个垂直平方数,而原始图像超过 11 个)。
-
你不想画到
clipRect。您希望以原始纵横比绘制图像,以便仅在clipRect中呈现您想要保留的部分。
标签: ios objective-c uiimage