我想创建一个固定大小的图像,例如612由612.我正在使用图像选择器从我的iphone选择照片。因此,为了确保所有照片都适合612×612大小而不失真,我使用以下方法重新缩放照片以使它们符合612的大小612。但是,因此,空白区域可能会在最终图像中创建。 (见下例)如何用颜色填充imageview(未被图像覆盖)的空白?
我使用下面的代码(由612固定大小612),以扩大我的形象
//Scale the image to fit to imageview
UIImage *image = [self scaleImage:img toRectSize:CGRectMake(0, 0, 612, 612)];
//Method to scale image
- (UIImage *)scaleImage:(UIImage *)img toRectSize:(CGRect)screenRect
{
UIGraphicsBeginImageContext(screenRect.size);
float hfactor = img.size.width/screenRect.size.width;
float vfactor = img.size.height/screenRect.size.height;
float factor = MAX(hfactor, vfactor);
float newWidth = img.size.width/factor;
float newHeight = img.size.height/factor;
float leftOffset = (screenRect.size.width - newWidth)/2;
float topOffset = (screenRect.size.height - newHeight)/2;
CGRect newRect = CGRectMake(leftOffset, topOffset, newWidth, newHeight);
[img drawInRect:newRect blendMode:kCGBlendModePlusDarker alpha:1];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
如前所述,作为图像有时是不完整的四边形,我得到一个导致像你看到下面的内容:
我怎么感觉了黑色图像中的空格?
谢谢!这是否意味着我必须删除此行[img drawInRect:newRect blendMode:kCGBlendModePlusDarker alpha:1];并用'ModeNormal'取代它?顺便说一句,这很好!非常感谢! – Zhen
是的。如果你想让实际的图像不受干扰,你必须使用* kCGBlendModeNormal *。 – EmptyStack