kursus
kursus

Reputation: 1404

Fill a resizable UIView with a transparent plain color that sticks to bounds

I have a UIImageView in a UIView.

media.mediaImageView = [UIImageView new];
media.mediaImageURL = [NSURL URLWithString:url];

media.mediaImageView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 120);
media.mediaImageView.contentMode = UIViewContentModeScaleAspectFill;
media.mediaImageView.clipsToBounds = YES;
[self.tableView addSubview:media.mediaImageView];

I would like to add a layer (or something else, a view ?) to that UIView, this layer would be filled with a plain color with alpha transparency. In the following example it would be redColor and transparency 0.5 :

enter image description here

But later in code the UIView is resized :

rect = CGRectMake(0, 0, newWidth, newHeight);
myUIView.frame = rect;

The color layer should automatically cover the entire UIView (whatever its size) without explicitly redrawing the layer. Is this possible ?

I can make it work but only by redrawing the UIView AND the layer.

Upvotes: 0

Views: 43

Answers (1)

rmaddy
rmaddy

Reputation: 318774

Easy enough. Add a subview to your image view. Set this view's background to the desired color. Set it's frame to match the image view's bounds. And be sure to set this view's autoresizingMask to have both flexible width and height. That will ensure it resizes automatically when the image view's size changes.

media.mediaImageView = [UIImageView new];
media.mediaImageURL = [NSURL URLWithString:url];

media.mediaImageView.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 120);
media.mediaImageView.contentMode = UIViewContentModeScaleAspectFill;
media.mediaImageView.clipsToBounds = YES;

// create and add overlay
UIView *overlay = [[UIView alloc] initWithFrame:media.mediaImageView.bounds];
overlay.backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.5]; // as needed
overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[media.mediaImageView addSubview:overlay];

Upvotes: 1

Related Questions