在 swift 中将 2 个视图与自定义颜色混合?

Blend 2 views with a custom color in swift?

在我的例子中,我需要这样的东西(绿色形状是动画的):

图片是用PaintCode创建的。为了实现这一点,我使用了 3 个对象: 1)标签为灰色文字颜色,混合为“差异” 2)带有绿色圆角的自定义形状 3)标签 - 与 1 相同,但混合和颜色参数不同 - 白色,混合为“叠加”

PaintCode 生成的代码:

//// General Declarations
let context = UIGraphicsGetCurrentContext()!

//// Color Declarations
let color2 = UIColor(red: 0.388, green: 0.714, blue: 0.557, alpha: 1.000)
let color3 = UIColor(red: 0.733, green: 0.733, blue: 0.733, alpha: 1.000)

//// Text Drawing
context.saveGState()
context.setBlendMode(.difference)

let textRect = CGRect(x: 49, y: 30, width: 108, height: 21)
let textTextContent = "Hello, World!"
let textStyle = NSMutableParagraphStyle()
textStyle.alignment = .left
let textFontAttributes = [
    .font: UIFont.systemFont(ofSize: UIFont.labelFontSize),
    .foregroundColor: color3,
    .paragraphStyle: textStyle,
] as [NSAttributedString.Key: Any]

let textTextHeight: CGFloat = textTextContent.boundingRect(with: CGSize(width: textRect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: textFontAttributes, context: nil).height
context.saveGState()
context.clip(to: textRect)
textTextContent.draw(in: CGRect(x: textRect.minX, y: textRect.minY + (textRect.height - textTextHeight) / 2, width: textRect.width, height: textTextHeight), withAttributes: textFontAttributes)
context.restoreGState()

context.restoreGState()


//// Rectangle Drawing
let rectanglePath = UIBezierPath(roundedRect: CGRect(x: 64, y: 30, width: 57, height: 47), byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 20, height: 20))
rectanglePath.close()
color2.setFill()
rectanglePath.fill()


//// Text 3 Drawing
context.saveGState()
context.setBlendMode(.overlay)

let text3Rect = CGRect(x: 49, y: 30, width: 108, height: 21)
let text3TextContent = "Hello, World!"
let text3Style = NSMutableParagraphStyle()
text3Style.alignment = .left
let text3FontAttributes = [
    .font: UIFont.systemFont(ofSize: UIFont.labelFontSize),
    .foregroundColor: UIColor.white,
    .paragraphStyle: text3Style,
] as [NSAttributedString.Key: Any]

let text3TextHeight: CGFloat = text3TextContent.boundingRect(with: CGSize(width: text3Rect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: text3FontAttributes, context: nil).height
context.saveGState()
context.clip(to: text3Rect)
text3TextContent.draw(in: CGRect(x: text3Rect.minX, y: text3Rect.minY + (text3Rect.height - text3TextHeight) / 2, width: text3Rect.width, height: text3TextHeight), withAttributes: text3FontAttributes)
context.restoreGState()

context.restoreGState()

问题是我不知道如何混合以用我需要的确切颜色填充交叉点。结果标签的颜色与我需要实现的颜色差别太大(灰色太暗,“白色”颜色是 ~(240, 255, 255) 而不是 (255, 255, 255))。

如何解决这个问题?解决方案可能不依赖于我指定的代码。

你不能用单纯的混合模式做到这一点。您需要使用 CIFilter。或者只使用两个标签,一个绿色,一个白色,然后用反向掩码将它们都遮住。