CG绘图在UIView中用作UIImage?

问题描述:

我正在尝试为UINavigationbar创建一个自定义的后退按钮。

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

我知道我可以使用 backButtonBackgroundImageForState:barMetrics:设置图像。

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.

我的问题是我可以继承UIView的类,重写drawrec:绘制后退按钮,然后将该UIView用作 backButtonBackgroundImageForState中的图像: barMetrics

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:

我在想这样的事情:

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];

这是否是解决此问题的最佳方法?还是我应该把它吸起来并在Photoshop中创建图像?

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

您可以使用 UIGraphicsBeginImageContextWithOptions 创建位图图像上下文,而无需创建 UIView 的子类并覆盖 drawRect:

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();