Resize UIImageView in UITableViewCell

后端 未结 4 1201
暖寄归人
暖寄归人 2020-12-16 03:51

I have a 16x16 pixel image that I want to display in an UIImageView. So far, no problem, however 16x16 is a bit small so I want to resize the image view to 32x32 and thus al

相关标签:
4条回答
  • 2020-12-16 04:04

    You need to override the layoutSubviews method. By default, it's resizing the imageview based on the cell height size.

    -(void)layoutSubviews
    {
        [super layoutSubviews];
    
        self.imageView.frame = CGRectMake(self.imageView.frame.origin.x,
                                          self.imageView.frame.origin.y,
                                          MY_ICON_SIZE,
                                          MY_ICON_SIZE);
    }
    

    You'll probably want to recalculate the origin as well so it's vertically centered.

    0 讨论(0)
  • 2020-12-16 04:18

    I have successfully made it using CGAffineTransformMakeScale!

    cell.imageView.image = cellImage;
    //self.rowWidth is the desired Width
    //self.rowHeight is the desired height
    CGFloat widthScale = self.rowWidth / cellImage.size.width;
    CGFloat heightScale = self.rowHeight / cellImage.size.height;
    //this line will do it!
    cell.imageView.transform = CGAffineTransformMakeScale(widthScale, heightScale);
    
    0 讨论(0)
  • 2020-12-16 04:20

    Using CGAffineTransformMakeScele as @ahmed said is valid and do not seems to be duck type solution at al! For instance, if you have a large image and put it into a UITableViewCell (say the image is 2x larger than the one that fits into a table cell. If you scale by 0.9 you don't see any result. Only if you scale by less than 0.5 (because 0.5*2.0 = 1.0 that is the size of the cell). So it seems that inside the api, apple is doing exactly that.

    0 讨论(0)
  • 2020-12-16 04:25

    I think you need to set the contentMode:

    cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
    

    In context:

    UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"slashdot" ofType:@"png"]];
    imageView = [[UIImageView alloc] initWithImage:image];
    [imageView setBackgroundColor:[UIColor greenColor]];
    [imageView setFrame:CGRectMake(x,y,32,32)];
    imageView.contentMode = UIViewContentModeScaleAspectFit;    
    [self.view addSubview:imageView];
    

    Note: I've set a background colour so you can debug the on-screen boundaries of the UIImageView. Also x and y are arbitrary integer coordinates.

    0 讨论(0)
提交回复
热议问题