【问题标题】:How can I dynamically set the size of the imageView according to the size of the image如何根据图片大小动态设置imageView的大小
【发布时间】:2012-05-17 10:13:06
【问题描述】:

我使用 Interface Builder 来布局我的视图和图像视图。我在视图上放了一个 imageView 并将其设置为插座。问题是无论我在程序中设置什么尺寸的图片(768*1024、1024*700):

 self.imageView.image = [UIImage imageNamed:self.filename];

要在屏幕上显示的大小始终是我在 Interface Builder 中设置的 imageView 的大小。如何根据图片大小动态设置imageView的大小?谢谢!

【问题讨论】:

    标签: iphone ipad uiimageview


    【解决方案1】:

    类似:

    UIImageView *imageView = [[UIImageView alloc] init];
    
    UIImage *image = [UIImage imageNamed:@"image.png"];
    CGSize imageSize = [image size];
    
    imageView.frame = CGRectMake(0, 0, imageSize.width, imageSize.height);
    

    【讨论】:

      【解决方案2】:
      UIImage *image = [UIImage imageNamed:self.filename];
      CGFloat width = image.size.width;
      CGFloat height = image.size.height;
      self.imageView.frame = CGRectMake(x, y , width, height);
      

      【讨论】:

        【解决方案3】:

        您可以对图像进行子类化,并在每次设置新图像时执行以下覆盖:

        @interface MyImageSubClass : UIImageView;
        @end
        
        @implementation MyImageSubClass
        
        - (void)setImage:(UIImage *)image {
            // Let the original UIImageView parent class do its job
            [super image];
        
            // Now set the frame according to the image size
            // and keeping the original position of your image frame
            if (image) {
                CGRect r = self.frame;
                CGSize imageSize = [image size];
                self.frame = (r.origin.x, r.origin.y, imageSize.width, imageSize.height);
            }
        }
        
        @end
        

        【讨论】:

          【解决方案4】:
           UIImage *buttonImage2=[UIImage imageNamed:@"blank_button_blue.png"];
           oButton=[[UIButton alloc] init];
           //  [oButton setImage:buttonImage2 forState:UIControlStateNormal];
           [oButton setFrame:CGRectMake(0, 0, buttonImage2.size.width, buttonImage2.size.height)];
          

          【讨论】:

            【解决方案5】:
            UIImage* sourceImage = [UIImage imageNamed:self.filename];;
            
             CGRect rect;
            rect.size.width = CGImageGetWidth(sourceImage.CGImage);
             rect.size.height = CGImageGetHeight(sourceImage.CGImage);
            
            [ yourimageview setframe:rect];
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-08-29
              • 2023-03-26
              • 2018-05-08
              相关资源
              最近更新 更多