简体   繁体   English

调整TableViewController单元格的图像大小

[英]Resize image of a TableViewController cell

I would like to resize the image of all the TableView cells i have. 我想调整我拥有的所有TableView单元格的图像的大小。 I tried this method and it's working but the quality of the image is decreased. 我尝试了这种方法,它可以工作,但是图像质量下降。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ 
//...
         CGSize size = {35,35};
         cell.imageView.image = [self imageWithImage:[UIImage imageNamed:@"image.png"] scaledToSize:size];
//...

}   

//Given a UIImage and a CGSize, this method will return a resized UIImage.
    - (UIImage*)imageWithImage:(UIImage*)image
           scaledToSize:(CGSize)newSize;
    {
        UIGraphicsBeginImageContext( newSize );
        [image drawInRect:CGRectMake(0,0,35,35)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return newImage;
    }

So i continued searching and i found someone saying to add this method 所以我继续搜索,发现有人说要添加此方法

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(0,0,35,35);
}

But Xcode gives me an error, is this method not available anymore? 但是Xcode给我一个错误,此方法不再可用吗?

How could i resize the image without losing quality? 如何调整图像大小而又不损失质量?

I manage to find a solution, here i'll explain in case someone will need. 我设法找到一个解决方案,如果有人需要,在这里我将解释。

First create a fake image, something like a white image or clear 首先创建伪造的图像,例如白色图像或清晰图像

cell.imageView.image = [UIImage imageNamed:@"clear.png"];

That's why you have to tell the cell there's an image. 这就是为什么您必须告诉单元格有图像的原因。 Now add an ImageView as a subview of the TableView cell 现在添加一个ImageView作为TableView单元的子视图

UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(20, 5, 35, 35)];
                imgView.backgroundColor=[UIColor clearColor];
                [imgView.layer setCornerRadius:8.0f];
                [imgView.layer setMasksToBounds:YES];
                [imgView setImage:[UIImage imageNamed:account.icon]];
                [cell.contentView addSubview:imgView];

Now it's good. 现在很好。 If you don't create the fake image the new created imgView will overlap the cell.textLabel.text 如果您不创建假图像,则新创建的imgView将与cell.textLabel.text重叠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM