如何为iOS中的按钮动态绘制图像?

How to dynamically draw image for button in iOS?

这是我需要完成的结果:

我需要带有基本图像的图标:篮子 另外我需要将带有一些文本的 UILabel 放在那里:一旦它只是一个数字,一旦它是一个数量支付。有什么想法吗?

这是我的例子:

var image = UIImage(named: "cart")!
let text = "1 PLN"

UIGraphicsBeginImageContext(CGSizeMake(80, 50))
let context = UIGraphicsGetCurrentContext()

let label = UILabel(frame: CGRectZero)
label.text = text
label.font = UIFont.systemFontOfSize(10)
label.sizeToFit()

let width = max(label.frame.size.width + 10, 15)
let height = CGFloat(15)

CGContextSetFillColorWithColor(context, UIColor.greenColor().CGColor)
CGContextFillRect(context, CGRectMake(0, 0, image.size.width,     image.size.height))

image.drawInRect(CGRectMake(80/2-50/2, 0, 50, 50))

let path = UIBezierPath(roundedRect: CGRectMake(75-width, 45-height, width, height), cornerRadius: 5)
path.lineWidth = 2
UIColor.redColor().setStroke()
UIColor.yellowColor().setFill()
path.stroke()
path.fill()

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Center
let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(10.0), NSParagraphStyleAttributeName: paragraphStyle]
(text as NSString).drawInRect(CGRectMake(75-width, 45-height, width, height), withAttributes: attributes)

let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

结果如下:

不同文本的一些示例: