Search code examples
ioscontentmode

UILabel for UIImageView that has contentMode UIViewContentModeScaleAspectFit


I need to set a label that has a custom background color on top of a UIImageView. The problem is that I want it's width to be the exact size as the image from the image view is. This is the code so far:

UIImageView *pictureV = [[UIImageView alloc] initWithFrame:CGRectMake(pictureX, 0, pictureSize.width, pictureSize.height)];
pictureV.image = self.picture.image;
pictureV.contentMode = UIViewContentModeScaleAspectFit;

And the label:

UILabel *lblName = [[UILabel alloc]init];
lblName.backgroundColor=[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.6];
lblName.frame = CGRectMake(pictureV.bounds.origin.x, pictureV.bounds.origin.y + pictureV.bounds.size.height - 30, self.picture.image.size.width, 30);
[lblName setText:self.pictureNote.text];
[lblName setTextAlignment:UITextAlignmentCenter];
[lblName setTextColor:[UIColor whiteColor]];
[pictureV addSubview:lblName]

When setting the contentMode as UIViewContentModeScaleAspectFit, some images are smaller than my UIImageView and I can't seem to make the label's width the same size.


Solution

  • If you use UIViewContentModeScaleAspectFit, the image will not take the full size of UIImage View. Instead of this set your pictureV's contentMode property to UIViewContentModeScaleToFill , then the image will take the whole size of your imageView