UIImageView在UICollectionViewCell子类中显示超出范围的图像

时间:2012-10-05 16:09:41

标签: objective-c uiimageview uiimage ios6 uicollectionview

我必须创建一个自定义的UICollectionViewCell来显示图像和图像的名称。在图像的顶部,有一个帧图像,其宽度和高度比图像大2个像素。但是,无论我做什么,图像似乎都比帧图像大。我为表格视图做了同样的事情,它完美无缺。

以下是代码:

//GridCell.h

@interface GridCell : UICollectionViewCell
@property(nonatomic, strong) UILabel *lblName;
@property(nonatomic, strong) UIImageView *image;
@end

//GridCell.m

#import "GridCell.h"

@implementation GridCell

@synthesize image, lblName;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        UIImage *bg = [UIImage imageNamed:@"borderUIimgLg.png"];

        UIImageView *bgImage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, frame.size.width, frame.size.width)];
        [bgImage setImage:bg];
        [bgImage setContentMode:UIViewContentModeScaleAspectFill];
         NSLog(@"BG Image size %f, %f", bgImage.frame.size.width, bgImage.frame.size.height);


        UIImageView *contentImage = [[UIImageView alloc] initWithFrame:CGRectMake(2.0, 2.0, frame.size.width-4.0, frame.size.width-4.0)];
        [contentImage setContentMode:UIViewContentModeScaleAspectFill];
        [contentImage setClipsToBounds:YES];
        self.image = contentImage;

        [self.contentView addSubview:self.image];

        [self.contentView addSubview:bgImage];

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(2.0, frame.size.width, frame.size.width - 4.0, 21.0)];
        [label setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:11.0]];
        [label setTextAlignment:NSTextAlignmentCenter];
        [label setBackgroundColor:[UIColor clearColor]];
        self.lblName = label;
        [self.contentView addSubview:self.lblName];
    }
    return self;
}

UICollectionViewCell的大小为67 x 100,因此在代码中,bgImage应始终为67 x 67,其原点为(0,0),而contentImage应为(0, 0,63,63)。通过调试,似乎是正确的。但是,conentimage总是比bgImage大。但是图像的原始尺寸为80 x 80。我试过setClipToBounds, 在cell.ContentView或imageView上使用setContentViewMode,但都不起作用。

附上了有关该问题的屏幕截图。Image in UIImage view out of bounds

感谢任何帮助。

3 个答案:

答案 0 :(得分:26)

现在可能已找到答案,请尝试:

contentImage.clipsToBounds = YES;

答案 1 :(得分:1)

你在另一个上使用2次frame.size.width而不是frame.size.height

编辑,试试这个:

单元格中的

,当使用initWithFrame方法时,请使用单元格的self.bounds属性。 如果在边框内初始化imageview,则使用CGRectInset方法初始化具有较小边界的imageview,并将imageviews center设置为与单元格的contentview相同

答案 2 :(得分:0)

尝试将UIViewContentModeScaleAspectFill更改为UIViewContentModeScaleAspectFit。