【问题标题】:Create a line graph with gradients in iOS在 iOS 中创建带有渐变的折线图
【发布时间】:2021-12-16 06:04:01
【问题描述】:

在 iOS 中创建这样的图表的最佳方法是什么?

我的第一个想法是创建一个贝塞尔路径,然后添加一个具有不同位置的渐变层。但这不起作用,因为文档指定:

这些值必须是单调递增的。

在我的图表中情况并非如此。

对实现这一目标的好方法有什么想法吗?

谢谢

【问题讨论】:

  • 渐变色代表什么?它似乎不随图表的 x 或 y 值变化。它是数据的第三维吗?
  • @jrturton 否,颜色数据与 Y 轴值相同。图片由设计师完成,因此并不能真正代表数据和视觉效果的实际外观。
  • @JoanCardona - “这不是真正的代表” ...如果您需要有关如何“做某事”的帮助,最好准确地展示您的内容想要做。发布一张看起来像你想要的东西的图片并不是很有帮助。

标签: ios swift gradient uibezierpath cagradientlayer


【解决方案1】:

您可以使用CAGradientLayer 作为图表的背景,然后使用CAShapeLayer 作为渐变层的蒙版来做到这一点。遮罩层只会在它被绘制的区域中显示下面的层。

这个操场代码给出了一个总体思路,使用随机生成的数据:

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
view.backgroundColor = .black

// Gradient for the chart colors
let gradient = CAGradientLayer()
gradient.colors = [
    UIColor.red.cgColor,
    UIColor.orange.cgColor,
    UIColor.yellow.cgColor,
    UIColor.green.cgColor
]
gradient.startPoint = CGPoint(x: 0.5, y: 0)
gradient.endPoint = CGPoint(x: 0.5, y: 1)

gradient.frame = view.bounds
view.layer.addSublayer(gradient)

// Random points
let graph = CAShapeLayer()
let path = CGMutablePath()
var y: CGFloat = 150
let points: [CGPoint] = stride(from: CGFloat.zero, to: 300, by: 2).map {
    let change = CGFloat.random(in: -20...20)
    var newY = y + change
    newY = max(10, newY)
    newY = min(newY, 300)
    y = newY
    return CGPoint(x: $0, y: y)
}
path.addLines(between: points)
graph.path = path
graph.fillColor = nil
graph.strokeColor = UIColor.black.cgColor
graph.lineWidth = 4
graph.lineJoin = .round
graph.frame = view.bounds

// Only show the gradient where the line is
gradient.mask = graph

PlaygroundPage.current.liveView = view

结果:

【讨论】:

  • 这太棒了,正是我所需要的,而且比我开发的要容易得多。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-10
  • 1970-01-01
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
相关资源
最近更新 更多