纵向图像未正确调整大小

时间:2014-03-21 10:50:30

标签: ios iphone objective-c uigraphicscontext

横向正确调整大小,但纵向图像未正确调整大小。 请有人帮我解决这个问题。 代码: -

CGSize newSize = CGSizeMake(width, height);

float widthRatio = newSize.width/image.size.width*image.scale;

float heightRatio = newSize.height/image.size.height*image.scale;

NSLog(@" image size %f %f %f",image.size.width,image.size.height,image.scale);

if(widthRatio > heightRatio)

    newSize=CGSizeMake(image.size.width*heightRatio,image.size.height*heightRatio);

 else

    newSize=CGSizeMake(image.size.width*widthRatio,image.size.height*widthRatio);

UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

2 个答案:

答案 0 :(得分:0)

试试这个:

- (UIImage*)resizeImage:(UIImage *)image imageSize:(CGSize)size {
    CGFloat imageWidth = image.size.width;
    CGFloat imageHeight = image.size.height;
    CGFloat requiredWidth = (imageWidth * size.height) / imageHeight;

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(requiredWidth, size.height), NO, [UIScreen mainScreen].scale);
    [image drawInRect:CGRectMake(0, 0, requiredWidth, size.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    //here is the scaled image which has been changed to the size specified
    UIGraphicsEndImageContext();
    return newImage;
}

答案 1 :(得分:0)

几天前我遇到了类似的问题。我试图使用UIImageView方法在较小的维度resizeImage中设置较大的维度图像,如此处的答案之一所述。但它无法解决我的问题。所以这就是我用来解决问题的方法,

yourImageView.contentMode = UIViewContentModeCenter;
[yourImageView setClipsToBounds:YES];

OR

[yourImageView setContentMode:UIViewContentModeScaleAspectFill];
yourImageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight );
[yourImageView setClipsToBounds:YES];

是的,它不会缩放您的图像,但您的图像不会被压扁。我用这个解决了我的问题,希望它可以解决你的问题。