CG drawing in UIView to use as UIImage?

2019-08-20 14:50发布

I am attempting to create a custom back button for UINavigationbar.

I know that I can use backButtonBackgroundImageForState:barMetrics: to set an image.

My problem is that I don't what to have to use an image file. I would rather draw the back button in code.

My question is can I subclass a UIView, override the drawrec: to draw a back button, then use that UIView as an image in backButtonBackgroundImageForState:barMetrics:

I'm thinking that it would go something like:

UIImage * backButtonImage = // somehow get image from my subclassed UIView;

backButtonImage = [backButtonImage stretchableImageWithLeftCapWidth: 15.0 topCapHeight: 30.0];

[[UIBarButtonItem appearance] setBackButtonBackgroundImage: backButtonImage forState: UIControlStateNormal barMetrics: UIBarMetricsDefault];

Is this even the best way to be going about this? Or should I just suck it up and create an image in photoshop?

1条回答
Bombasti
2楼-- · 2019-08-20 15:35

You can create a bitmap image context using UIGraphicsBeginImageContextWithOptions, without making a subclass of UIView and overriding drawRect:.

UIGraphicsBeginImageContextWithOptions(CGSizeMake(80, 30), NO, 0);
// drawing code here
// Use UIKit functions and objects
// or use CoreGraphics functions on UIGraphicsGetCurrentContext()
UIImage *image = UIGraphicsGetImageFromCurrentContext();
UIGraphicsEndImageContext();
查看更多
登录 后发表回答