ios - Swift - 如何使用 UIGraphics 混合模式?

标签 ios swift watchkit uigraphicscontext

我想为AppleWatch开发一种进度条动画。 我决定使用 UIGraphicContext 来完成这一切。

由于我是一个完全的初学者,所以我不太明白如何将某种“globalCompositeOperation”应用到我的上下文中。

为了更好地说明我的想法,这里有一些图片:

Image #1

Image #2

Image #3


这是我到目前为止的源代码:

let size = CGSize(width: 300, height: 100)
UIGraphicsBeginImageContext(size)

let context = UIGraphicsGetCurrentContext()!

context.setFillColor(UIColor.red.cgColor)
context.fill(CGRect(x: 0.0, y: 0.0, width: size.width * 0.5, height: size.height))
context.setBlendMode(CGBlendMode.destinationOver)

let count = 5;
let padding = (size.width / CGFloat(count)) * 0.5
for i in 0...count {
    let offsetX = size.width * (CGFloat(i) / CGFloat(count))
    let rect = CGRect(x: offsetX + padding/2, y: 0, width: padding, height: size.height)
    context.setFillColor(UIColor.green.cgColor)
    context.fill(rect)
}
UIGraphicsEndImageContext()

我想这是一种错误的方法,因为结果更像是这样的:

Image #4

任何帮助将不胜感激。提前致谢。

最佳答案

您需要.sourceAtop。这是一个演示:

    let green = UIImage(named:"green.png")! // your original 5 green rects
    let sz = green.size
    let red = UIGraphicsImageRenderer(size:sz).image {
        ctx in
        UIColor.red.setFill()
        // width value determines how much we will fill
        ctx.fill(CGRect(x: 0, y: 0, width: sz.width/2, height: sz.height))
    }
    let result = UIGraphicsImageRenderer(size:sz).image {
        ctx in
        green.draw(at: .zero)
        red.draw(at: .zero, blendMode: .sourceAtop, alpha: 1)
    }

enter image description here

只需改变 width: sz.width/2 的值即可获得不同的“温度计”量。

关于ios - Swift - 如何使用 UIGraphics 混合模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59909716/

相关文章:

ios - 使用 Core Graphics 合成图像并保留 alpha channel

android - 当我从 flutter 的 Assets 中获取时的ImageIcon颜色问题

ios - PHAssetResource.assetResources(对于 : asset). first.OriginalFilename 在 300 个 Assets 后给出 nil

ios - WCSession - PayloadTooLarge

ios - 将 AFNetworking 添加到 Watchkit

ios - 在道路上随机放置图钉 - iOS Maps Swift

android - PWA 在后台播放媒体

ios - UITabBar 边框和阴影问题

ios - 事件指示器未出现

ios - 无法为 Watch Extension 创建专用 App ID