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

Zha*_*hao 6 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;
}
Run Code Online (Sandbox Code Playgroud)

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

附上有关该问题的屏幕截图.UIImage视图中的图像超出界限

任何帮助表示赞赏.

use*_*687 26

这可能现在找到了答案,尝试:

contentImage.clipsToBounds = YES;
Run Code Online (Sandbox Code Playgroud)


Phi*_*olb 1

您使用了两倍的frame.size.width,而不是另一倍的frame.size.height

编辑,试试这个:

在单元格中,使用 initWithFrame 方法时,请使用单元格的 self.bounds 属性。如果您在边框内初始化图像视图,请使用 CGRectInset 方法以较小的边界初始化图像视图,并将图像视图中心设置为与单元格的内容视图相同