UIView background image resize

2019-05-31 05:48发布

I have a UIView (that is my navigation drawer) and I want to set a background image. First I have tried this approach:

menuView.backgroundColor = UIColor(patternImage: UIImage(named: "menu_image.png")!)

But I get only a part of my image that fills my UIView. So next I have tried to resize image like this:

UIGraphicsBeginImageContext(menuView.frame.size);
var image = UIImage(named: "menu_image.png")
image?.drawInRect(menuView.bounds)
UIGraphicsEndImageContext()
menuView.backgroundColor = UIColor(patternImage: image!)

But it doesn't help and it is strange, bcs people said, that it helped them. I don't understand what I am doing wrong.

Update

I forgot 1 line:

UIGraphicsBeginImageContext(menuView.frame.size);
var image = UIImage(named: "menu_image.png")
image?.drawInRect(menuView.bounds)
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
menuView.backgroundColor = UIColor(patternImage: image!)

Question is closed, thx.

标签: ios swift uiview
1条回答
乱世女痞
2楼-- · 2019-05-31 06:14

Obj-C ... convert it to Swift and it will work (u're missing one line)

UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"image.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.view.backgroundColor = [UIColor colorWithPatternImage:image];
查看更多
登录 后发表回答