几天来,我一直在努力解决这个问题,尽管我一直觉得自己正处于启示的边缘,但我根本无法实现我的目标。
在设计的概念阶段之前,我认为从 iPhone 的相机或库中抓取图像,使用相当于宽高比填充UIImageView 的选项(完全在代码中),然后crop off任何不适合传递的 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)