我正在尝试使用swift 4在我的应用程序中创建一个聊天应用程序。
我希望聊天气泡以渐变颜色显示,我以编程方式设置。
我通过将图像渲染为模板来实现纯色,如下所示:
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
怎么做?
更新:我是由Mr.Matt解决方案制作的,但我在调整尺寸方面遇到了一些麻烦。这是我在课堂上制作后的最终代码:
类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")
}
}
最终结果如下:
我希望渐变气泡大小与黑色气泡大小完全相同。