嘗試使用此代碼.. 爲圓按鈕,圖像 -
let button = UIButton()
button.frame = CGRectMake(0, 0, 40, 40)
let color = UIColor(patternImage: UIImage(named: "btnImage")!)
button.backgroundColor = color
button.layer.cornerRadius = 0.5 * button.bounds.size.width
let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.rightBarButtonItem = barButton
實際圖像---
let button = UIButton()
button.frame = CGRectMake(0, 0, 40, 40)
let image = UIImage(named: "btnImage")!
UIGraphicsBeginImageContextWithOptions(button.frame.size, false, image.scale)
let rect = CGRectMake(0, 0, button.frame.size.width, button.frame.size.height)
UIBezierPath(roundedRect: rect, cornerRadius: rect.width/2).addClip()
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let color = UIColor(patternImage: newImage)
button.backgroundColor = color
button.layer.cornerRadius = 0.5 * button.bounds.size.width
let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.rightBarButtonItem = barButton
基本上你應該創建一個圖像的顏色來設置,然後設置按鈕的背景顏色 –
它的工作原理,但這也裁剪圖像。我不想裁剪我的圖像 –
我有這個解決方案。我編輯了我的答案..如果這或我早期的解決方案解決您的問題,請檢查此答案。 –