代码之家  ›  专栏  ›  技术社区  ›  JustSid

在UITableViewCell中调整UIImageView的大小

  •  8
  • JustSid  · 技术社区  · 14 年前

    我有一个16x16像素的图像,我想在UIImageView中显示。到目前为止,没问题,不过16x16有点小,所以我想把图像视图调整到32x32,这样也可以放大图像。 但我不能让它工作,它总是显示16x16的图像,无论我尝试什么。我搜索了很多,在堆栈溢出上发现了很多片段,但仍然不起作用。 这是我目前的代码:

    [[cell.imageView layer] setMagnificationFilter:kCAFilterNearest];
    [cell.imageView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
    [cell.imageView setClipsToBounds:NO];
    [cell.imageView setFrame:CGRectMake(0, 0, 32, 32)];
    [cell.imageView setBounds:CGRectMake(0, 0, 32, 32)];
    [cell.imageView setImage:image];
    

    我不想创建一个新的32x32像素的图像,因为我在旧设备上已经有一些内存问题,创建两个图像而不是只有一个看起来对我来说是一个非常糟糕的方法(图像可以完全缩放,如果它们失去质量也无所谓)。

    4 回复  |  直到 14 年前
        1
  •  29
  •   Ahmed    13 年前

    我已经成功地使用cgafinetransformmakescale!

    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);
    
        2
  •  4
  •   searlea    14 年前

    我想你需要设置contentMode:

    cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
    

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

    注意:我已经设置了背景颜色,这样您就可以调试UIImageView的屏幕边界。阿尔索 x y

        3
  •  1
  •   ninguem    12 年前

    使用 CGAffineTransformMakeScele 正如艾哈迈德所说,这是有效的,似乎不是鸭式解决方案在阿尔!例如,如果您有一个大图像并将其放入UITableViewCell中(假设该图像比适合表单元格的图像大2倍)。如果按0.9缩放,则看不到任何结果。仅当缩放小于0.5时(因为0.5*2.0=1.0即单元格大小)。因此,在api内部,苹果似乎正是这么做的。

        4
  •  1
  •   Jason    10 年前

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

    您可能还需要重新计算原点,使其垂直居中。