Thomas
10/24/2019, 7:59 PMimport UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let layer = createGradient()
layer.frame = self.view.bounds
self.view.layer.addSublayer(layer)
}
func createGradient() -> CAGradientLayer {
let layer = CAGradientLayer()
layer.type = kCAGradientLayerAxial
layer.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
return layer
}
}
I would like to convert the createGradient function to Kotlin. This is what I have tried:
import platform.QuartzCore.CAGradientLayer
import platform.QuartzCore.kCAGradientLayerAxial
import platform.UIKit.UIColor
fun createGradient(): CAGradientLayer {
val layer = CAGradientLayer()
layer.type = kCAGradientLayerAxial
layer.colors = listOf(UIColor.redColor.CGColor, UIColor.blueColor.CGColor)
return layer
}
When using this function the layer just doesn’t appear on the screen. As if it is completely transparent. I think something could be going wrong with the colors. Could anyone here help me out?svyatoslav.scherbina
10/25/2019, 8:46 AMCGColorRef
is CoreFoundation type.
Current interop implementation in Kotlin doesn’t handle CoreFoundation types as reference types and doesn’t automatically bridge them to Objective-C references, so you have to bridge explicitly here, properly handling memory management.
Consider taking a look at https://developer.apple.com/documentation/foundation/1587932-cfbridgingreleaseThomas
10/25/2019, 9:56 AMfun createGradient(): CAGradientLayer {
val layer = CAGradientLayer()
layer.type = kCAGradientLayerAxial
val colors = listOf(UIColor.redColor.CGColor, UIColor.blueColor.CGColor)
layer.colors = colors.map { CFBridgingRelease(it) }
return layer
}
svyatoslav.scherbina
10/25/2019, 10:50 AMCFRetain
here.