【问题标题】:Resize UIImageView in iOS在 iOS 中调整 UIImageView 的大小
【发布时间】:2013-12-02 07:03:38
【问题描述】:

我正在使用 SDWebImage 使用 iCarossel。一切正常,但是当图像尺寸太大时,它就会消失在屏幕之外。

下面是生成图像视图的sn-p

view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];

[((UIImageView *)view) setImageWithURL:[NSURL URLWithString:@"http://www.pizzatower.com/img/icons/Pizza-icon.png"]];
//        [((UIImageView *)view) setImageWithURL:[NSURL URLWithString:@"http://www.rivercitypizza.com/PepperoniPizza-full.jpg"]];

view.contentMode = UIViewContentModeCenter;
view.frame = CGRectMake(0, 0, 256, 256);
label = [[UILabel alloc] initWithFrame:view.bounds];
label.backgroundColor = [UIColor clearColor];
label.font = [label.font fontWithSize:10];
label.tag = 1;
[view addSubview:label];

我尝试更改 frame 属性,但没有任何变化。有人可以指出如何调整图像大小并将其保持在屏幕大小范围内吗?

【问题讨论】:

  • 可能你要设置uiimageview属性contentMode

标签: ios uiimageview sdwebimage icarousel


【解决方案1】:

如果您使用view.contentMode = UIViewContentModeScaleAspectFit;,您的图像将被缩放以适合框架内。

【讨论】:

【解决方案2】:
  1. 设置你的 UIImageView ContentMode

    YourImageView.contentMode=UIViewContentModeScaleToFill;

  2. 使用此代码

在你的代码中写下这一行。

UIImage *ResizeImage=[self resizeImage:YourMainUIImage resizeSize:CGSizeMake(100,100)];

在您的 ViewController 中添加添加此方法

-(UIImage *) resizeImage:(UIImage *)orginalImage resizeSize:(CGSize)size
{
    CGFloat actualHeight = orginalImage.size.height;
    CGFloat actualWidth = orginalImage.size.width;

    float oldRatio = actualWidth/actualHeight;
    float newRatio = size.width/size.height;
    if(oldRatio < newRatio)
    {
        oldRatio = size.height/actualHeight;
        actualWidth = oldRatio * actualWidth;
        actualHeight = size.height;
    }
    else
    {
        oldRatio = size.width/actualWidth;
        actualHeight = oldRatio * actualHeight;
        actualWidth = size.width;
    }

    CGRect rect = CGRectMake(0.0,0.0,actualWidth,actualHeight);
    UIGraphicsBeginImageContext(rect.size);
    [orginalImage drawInRect:rect];
    orginalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return orginalImage;
}

【讨论】:

    【解决方案3】:

    试试这个:

      UIImage *resizedImage = [self imageWithImage:self.image scaledToSize:CGSizeMake(768, 1024)];
    
    - (UIImage *)imageWithImage:(UIImage *)imagee scaledToSize:(CGSize)newSize {
        //UIGraphicsBeginImageContext(newSize);
        // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
        // Pass 1.0 to force exact pixel size.
        UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
        [imagee drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
    }
    

    【讨论】: