几天来,我一直在用自己的脸来面对这个问题,尽管我一直觉得自己正处于启示的边缘,但我根本无法实现我的目标。
我认为,在我设计的概念阶段提前,从 iPhone 的相机或库中抓取图像,将其缩小到指定的高度,使用相当于 Aspect Fill 选项的功能将是一件小事UIImageView(完全在代码中),然后 裁剪掉 任何不适合传递的 CGRect 的内容。
从相机或图书馆获取原始图像是微不足道的。我对其他两个步骤被证明是多么困难感到震惊。
附图显示了我想要实现的目标。有人会好心地握住我的手吗?到目前为止,我发现的每个代码示例似乎都会破坏图像、颠倒、看起来像废话、绘制越界或无法正常工作。
我需要同样的东西——在我的例子中,选择适合缩放后的尺寸,然后裁剪每一端以适应其余部分的宽度。(我在横向工作,所以可能没有注意到纵向模式的任何缺陷。)这是我的代码 - 它是 UIImage 类别的一部分。我的代码中的目标大小始终设置为设备的全屏大小。
@implementation UIImage (Extras) #pragma mark - #pragma mark Scale and crop image - (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize { UIImage *sourceImage = self; UIImage *newImage = nil; CGSize imageSize = sourceImage.size; CGFloat width = imageSize.width; CGFloat height = imageSize.height; CGFloat targetWidth = targetSize.width; CGFloat targetHeight = targetSize.height; CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; CGPoint thumbnailPoint = CGPointMake(0.0,0.0); if (CGSizeEqualToSize(imageSize, targetSize) == NO) { CGFloat widthFactor = targetWidth / width; CGFloat heightFactor = targetHeight / height; if (widthFactor > heightFactor) { scaleFactor = widthFactor; // scale to fit height } else { scaleFactor = heightFactor; // scale to fit width } scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; // center the image if (widthFactor > heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else { if (widthFactor < heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } } UIGraphicsBeginImageContext(targetSize); // this will crop CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = thumbnailPoint; thumbnailRect.size.width = scaledWidth; thumbnailRect.size.height = scaledHeight; [sourceImage drawInRect:thumbnailRect]; newImage = UIGraphicsGetImageFromCurrentImageContext(); if(newImage == nil) { NSLog(@"could not scale image"); } //pop the context to get back to the default UIGraphicsEndImageContext(); return newImage; }