ios - How can I programatically add a Gradient Layer over an image in Swift? -
i want place layer predefined transparent black gradient on top of uiimage content image loaded via web , creating effect of shadow on it.
i don't want via loading png such gradient.
i suggest creating custom subclass of uiview (or uiimageview, if want add gradient uiimageview). in init method of custom view, create cagradientlayer , add sublayer of view's layer. set black transparent gradient on layer.
you need override layoutsubviews() , change settings on gradient layer in case view's bounds change.
edit:
i created playground gist on github working example of this:
the code looks this:
import uikit import avfoundation class imageviewwithgradient: uiimageview { let mygradientlayer: cagradientlayer override init(frame: cgrect) { mygradientlayer = cagradientlayer() super.init(frame: frame) self.setup() } required init(coder adecoder: nscoder) { mygradientlayer = cagradientlayer() super.init(coder: adecoder) self.setup() } func setup() { mygradientlayer.startpoint = cgpoint(x: 0, y: 0) mygradientlayer.endpoint = cgpoint(x: 1, y: 1) let colors: [cgcolorref] = [ uicolor.clearcolor().cgcolor, uicolor(red: 0, green: 0, blue: 0, alpha: 0.3).cgcolor, uicolor(red: 1, green: 1, blue: 1, alpha: 0.5).cgcolor, uicolor(red: 0, green: 0, blue: 0, alpha: 0.3).cgcolor, uicolor.clearcolor().cgcolor ] mygradientlayer.colors = colors mygradientlayer.opaque = false mygradientlayer.locations = [0.0, 0.3, 0.5, 0.7, 1.0] self.layer.addsublayer(mygradientlayer) } override func layoutsubviews() { mygradientlayer.frame = self.layer.bounds } } var aview = imageviewwithgradient(frame: cgrect(x: 0, y: 0, width: 500, height: 500))
Comments
Post a Comment