gpt4 book ai didi

swift - 快速获取需要与另一种颜色合成的颜色以得到目标颜色

转载 作者:行者123 更新时间:2023-11-30 11:48:21 27 4
gpt4 key购买 nike

我使用 NSTableViewNSTableCellView(s) 中绘制一些信息。我想将 NSTableView 的背景颜色设置为某个值,将 NSTableCellView 的背景颜色设置为另一个值,而与所用颜色的 alpha 分量无关。问题是,如果我为 NSTableCellView 设置 alpha 分量 0.3 的背景颜色,我们会看到 NSTableView 的背景颜色,然后颜色不是我设置的颜色。

我看到有两个选项可以解决这个问题:

  1. 绘制 NSTableView 的背景颜色,而不在 NSTableCellView(s) 使用的矩形下绘制。
  2. 使用颜色理论和 CoreGraphics 来计算新颜色。

我已经解决了一点选项 1,但没有得到任何结果。我现在正在更多地研究选项 2。

例如,如果我有两种颜色:

let tableViewBackgroundColor = NSColor(calibratedRed: 48/255, green: 47/255, blue: 46/255, alpha: 1)

let tableViewCellBackgroundColor = NSColor(calibratedRed: 42/255, green: 41/255, blue: 40/255, alpha: 1)

我想要将结果颜色应用于 NSTableCellView 背景:

let targetColor = tableViewCellBackgroundColor.withAplphaComponent(0.3)

即使颜色:

let tableViewBackgroundColorWithAlpha = tableViewBackgroundColor.withAlphaComponent(0.3)

应用于NSTableView的背景。

我正在寻找 NSColor 的扩展(CGColor 可以工作),如下所示:

extension NSColor {

///
/// Return the color that needs to be composed with the color parameter
/// in order to result in the current (self) color.
///
func composedColor(with color: NSColor) -> NSColor

}

可以这样使用:

let color = targetColor.composedColor(with: 
tableViewBackgroundColorWithAlpha)

有什么想法吗?

最佳答案

回答我自己的问题,这个问题的解决方案最终是避免使用表格 View 单元格绘制零件(问题的选项1)。我的灵感来自Drawing Custom Alternating Row Backgrounds in NSTableViews with Swift来实现最终的解决方案。

它基本上涉及覆盖NSTableView的方法func drawBackground(inClipRect ClipRect: NSRect),但避免绘制存在单元格的表格的背景部分。

解决办法如下:

override func drawBackground(inClipRect clipRect: NSRect) {

super.drawBackground(inClipRect: clipRect)

drawTopBackground(inClipRect: clipRect)
drawBottomBackground(inClipRect: clipRect)
}

private func drawTopBackground(inClipRect clipRect: NSRect) {

guard clipRect.origin.y < 0 else { return }

let rectHeight = rowHeight + intercellSpacing.height
let minY = NSMinY(clipRect)
var row = 0
currentBackgroundColor.setFill()

while true {

let rowRect = NSRect(x: 0, y: (rectHeight * CGFloat(row) - rectHeight), width: NSMaxX(clipRect), height: rectHeight)

if self.rows(in: rowRect).isEmpty {
rowRect.fill()
}
if rowRect.origin.y < minY { break }
row -= 1
}
}

private func drawBottomBackground(inClipRect clipRect: NSRect) {

let rectHeight = rowHeight + intercellSpacing.height
let maxY = NSMaxY(clipRect)
var row = rows(in: clipRect).location
currentBackgroundColor.setFill()

while true {

let rowRect = NSRect(
x: 0,
y: (rectHeight * CGFloat(row)),
width: NSMaxX(clipRect),
height: rectHeight)

if self.rows(in: rowRect).isEmpty {
rowRect.fill()
}
if rowRect.origin.y > maxY { break }
row += 1
}
}

关于swift - 快速获取需要与另一种颜色合成的颜色以得到目标颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48576165/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com