Mit Bezug auf den obigen Kommentar.
Mein Code:
button.backgroundColor = UIColor.withAlphaComponent(UIColor.white)(0.1)
button.layer.cornerRadius = button.frame.size.height/2
button.layer.borderWidth = 3
button.layer.borderColor = UIColor.white.cgColor
button.layer.contents = UIImage(named: "buttonImage.png")?.cgImage
button.layer.contentsGravity = kCAGravityCenter
button.layer.magnificationFilter = kCAFilterLinear
button.layer.isGeometryFlipped = false
Anwendung der Lösung:
let maskLayer = CALayer()
Und schließlich:
layer.backgroundColor = UIColor.redColor().CGColor
Das Ergebnis ist schrecklich.
Die Lösung ist auf den unten stehenden Link (Link im Kommentar)
Aber ich zeige meinen Code (nehmen Sie es von Link):
let image_ = UIImage(named: "image.png")
let maskImage = image_?.cgImage
let width = image_?.size.width
let height = image_?.size.height
let bounds = CGRect(x: 0, y: 0, width: width!, height: height!)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let bitmapContext = CGContext(data: nil,
width: Int(width!),
height: Int(height!),
bitsPerComponent: 8,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue)
bitmapContext?.clip(to: bounds, mask: maskImage!)
bitmapContext?.setFillColor(UIColor.yellow.cgColor)
bitmapContext?.fill(bounds)
let cImage = bitmapContext?.makeImage()
let coloredImage = UIImage(cgImage: cImage!)
self.myUIButton.layer.contents = coloredImage.cgImage
Bitte, lassen Sie mich Ihnen etwas sagen (ist wichtig) spielen Sie nicht mit:
Der Bildname "someImage.png" muss genau der Dateiname in Ihrem Projektordner sein.
viel einfacher und sauberer als die angenommene Antwort. Vielleicht möchten Sie es vollständiger machen, indem Sie level layer = CALayer() hinzufügen und layer.frame einstellen. –
Nicht für mich arbeiten. Dann schreibe meinen Code: – Markus