ios - Swift 4 中模板图像的渐变颜色

标签 ios swift uiimageview uiimage

我正在尝试使用 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")
}

}

最终结果如下:

Masked Gradient

我希望渐变气泡大小与黑色气泡大小完全相同。

最佳答案

绘制渐变(CAGradientLayer 是最简单的方法)。然后使用气泡形状来掩盖渐变。

例如,这是一个示例气泡形状:

enter image description here

这是掩盖红色到橙色渐变的形状:

enter image description here

现在您可以将文本放入气泡内(作为标签、CATextLayer 或任何方便的内容)。

关于ios - Swift 4 中模板图像的渐变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47122957/

相关文章:

ios - SuperpoweredAdvancedAudioPlayer 无法在 iOS13 中打开 "ipod-library"路径

ios - UITableViewCell Storyboard 注册依赖于初始 View Controller ?

ios - UIImageView 正在显示放大的图像

ios - Swift Play 视频无法显示

ios - 如何快速将结构编码和解码为 NSData?

ios - UITextField inputView - IBActions 未触发

ios - 安装 pod Alamofire 时出现错误

ios - 数组扩展通用 Equatable - "Cannot invoke ' = =' with ..."

ios - 圆角半径图像 Swift

ios - Xamarin iOS - UIScrollView 内的 UIImageView 在方向改变后移位