在iOS中调整UIImageView的大小

时间:2013-12-02 07:03:39

标签: ios uiimageview sdwebimage icarousel

我正在使用SDWebImage来使用iCarossel。一切都很好,但是当图像尺寸太大时,它就会离开屏幕。

以下是生成图像视图的代码段

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属性,但没有任何变化。有人能指出我如何调整图像大小并将其保持在屏幕大小范围内吗?

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

  1. 设置您的UIImageView ContentMode

    YourImageView.contentMode = UIViewContentModeScaleToFill;

  2. 使用此代码

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

    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;
    }
    

答案 2 :(得分:1)

试试这个:

  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;
}