I am trying to make a chat app in my application using swift 4.
I want the chat bubble to appear with gradient color That I set programatically.
I Achieved That by a solid color by rendering the image as template as the following:
let TestImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
let TestImage = ChatBubble
let TestImage2 = TestImage.resizableImage(withCapInsets: TestInsets, resizingMode: .stretch).withRenderingMode(UIImageRenderingMode.alwaysTemplate)
TestImageView.image = TestImage2
TestImageView.tintColor = UIColor.red
How to do it?
Update: I made it by Mr.Matt solution but I went through some troubles in sizing. This is my Final Code after Making it inside a class:
class UIChatBubbleView: UIView {
override func draw(_ rect: CGRect) {
let ChatBubbleView = UIImageView(frame: rect)
let BubbleInsets = UIEdgeInsets(top: 100, left: 200, bottom: 240, right: 240)
let BubbleImage = #imageLiteral(resourceName: "ChatBubble").resizableImage(withCapInsets: BubbleInsets, resizingMode: .stretch)
ChatBubbleView.image = BubbleImage
let MyView = UIView(frame: ChatBubbleView.bounds)
MyView.layer.contents = ChatBubbleView.image?.cgImage
let GradientLayer = CAGradientLayer()
GradientLayer.frame = ChatBubbleView.bounds
GradientLayer.colors = [UIColor.red.cgColor,UIColor.blue.cgColor]
GradientLayer.mask = ChatBubbleView.layer
MyView.layer.addSublayer(GradientLayer)
MyView.layer.shadowColor = UIColor.black.cgColor
MyView.layer.shadowOffset = CGSize(width: 3.0, height: 3.0)
MyView.layer.shadowOpacity = 0.5
MyView.layer.shadowRadius = 3
self.addSubview(MyView)
}
override init(frame:CGRect) {
super.init(frame:frame)
self.isOpaque = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
The final result appeared like this:
I want the gradient bubble size to be exactly as the black one.