Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added gradient line drawing to LineChartRenderer #3142

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ open class LineChartDataSet: LineRadarChartDataSet, LineChartDataSetProtocol
}
}
}


open var isDrawLineWithGradientEnabled = false

open var gradientPositions: [CGFloat]?

/// The radius of the drawn circles.
open var circleRadius = CGFloat(8.0)

Expand Down
8 changes: 7 additions & 1 deletion Source/Charts/Data/Interfaces/LineChartDataSetProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,13 @@ public protocol LineChartDataSetProtocol: LineRadarChartDataSetProtocol
///
/// **default**: 0.2
var cubicIntensity: CGFloat { get set }


/// If true, gradient lines are drawn instead of solid
var isDrawLineWithGradientEnabled: Bool { get set }

/// The points where gradient should change color
var gradientPositions: [CGFloat]? { get set }

/// The radius of the drawn circles.
var circleRadius: CGFloat { get set }

Expand Down
163 changes: 144 additions & 19 deletions Source/Charts/Renderers/LineChartRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -161,21 +161,27 @@ open class LineChartRenderer: LineRadarRenderer
}

context.saveGState()

defer { context.restoreGState() }

if dataSet.isDrawFilledEnabled
{
// Copy this path because we make changes to it
let fillPath = cubicPath.mutableCopy()

drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds)
}

context.beginPath()
context.addPath(cubicPath)
context.setStrokeColor(drawingColor.cgColor)
context.strokePath()

context.restoreGState()

if dataSet.isDrawLineWithGradientEnabled
{
drawGradientLine(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix)
}
else
{
context.beginPath()
context.addPath(cubicPath)
context.setStrokeColor(drawingColor.cgColor)
context.strokePath()
}
}

@objc open func drawHorizontalBezier(context: CGContext, dataSet: LineChartDataSetProtocol)
Expand Down Expand Up @@ -247,10 +253,10 @@ open class LineChartRenderer: LineRadarRenderer

open func drawCubicFill(
context: CGContext,
dataSet: LineChartDataSetProtocol,
spline: CGMutablePath,
matrix: CGAffineTransform,
bounds: XBounds)
dataSet: LineChartDataSetProtocol,
spline: CGMutablePath,
matrix: CGAffineTransform,
bounds: XBounds)
{
guard
let dataProvider = dataProvider
Expand Down Expand Up @@ -307,7 +313,8 @@ open class LineChartRenderer: LineRadarRenderer
}

context.saveGState()

defer { context.restoreGState() }

context.setLineCap(dataSet.lineCapType)

// more than 1 color
Expand Down Expand Up @@ -416,8 +423,8 @@ open class LineChartRenderer: LineRadarRenderer
}

context.addLine(to: CGPoint(
x: CGFloat(e2.x),
y: CGFloat(e2.y * phaseY)
x: CGFloat(e2.x),
y: CGFloat(e2.y * phaseY)
).applying(valueToPixelMatrix))
}

Expand All @@ -428,8 +435,17 @@ open class LineChartRenderer: LineRadarRenderer
}
}
}

context.restoreGState()

if (dataSet.isDrawLineWithGradientEnabled)
{
let path = generateGradientLinePath(dataSet: dataSet,
fillMin: dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0,
from: _xBounds.min,
to: _xBounds.max,
matrix: trans.valueToPixelMatrix)

drawGradientLine(context: context, dataSet: dataSet, spline: path, matrix: valueToPixelMatrix)
}
}

open func drawLinearFill(context: CGContext, dataSet: LineChartDataSetProtocol, trans: Transformer, bounds: XBounds)
Expand Down Expand Up @@ -680,7 +696,7 @@ open class LineChartRenderer: LineRadarRenderer
if drawCircleHole
{
context.setFillColor(dataSet.circleHoleColor!.cgColor)

// The hole rect
rect.origin.x = pt.x - circleHoleRadius
rect.origin.y = pt.y - circleHoleRadius
Expand Down Expand Up @@ -719,7 +735,7 @@ open class LineChartRenderer: LineRadarRenderer
{
continue
}

context.setStrokeColor(set.highlightColor.cgColor)
context.setLineWidth(set.highlightLineWidth)
if set.highlightLineDashLengths != nil
Expand Down Expand Up @@ -751,4 +767,113 @@ open class LineChartRenderer: LineRadarRenderer

context.restoreGState()
}

/// Generates the path that is used for gradient drawing.
private func generateGradientLinePath(dataSet: LineChartDataSetProtocol, fillMin: CGFloat, from: Int, to: Int, matrix: CGAffineTransform) -> CGPath
{
let phaseX = CGFloat(animator.phaseX)
let phaseY = CGFloat(animator.phaseY)

var e: ChartDataEntry!

let generatedPath = CGMutablePath()
e = dataSet.entryForIndex(from)
if e != nil
{
generatedPath.move(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y) * phaseY), transform: matrix)
}

// create a new path
let to = Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from)))
for i in (from + 1)..<to
Copy link

@natacodes natacodes Dec 30, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_xBounds.max and _xBounds.min can be zeros when there's only one data entry and this for is crashing the app with Fatal error: Can't form Range with upperBound < lowerBound

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It needs if dataSet.entryCount > 1 somewhere.

{
guard let e = dataSet.entryForIndex(i) else { continue }
generatedPath.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y) * phaseY), transform: matrix)
}
return generatedPath
}

func drawGradientLine(context: CGContext, dataSet: LineChartDataSetProtocol, spline: CGPath, matrix: CGAffineTransform)
{
context.saveGState()
defer { context.restoreGState() }

let gradientPath = spline.copy(strokingWithWidth: dataSet.lineWidth, lineCap: .butt, lineJoin: .miter, miterLimit: 10)
context.addPath(gradientPath)
context.drawPath(using: .fill)

let boundingBox = gradientPath.boundingBox
let gradientStart = CGPoint(x: 0, y: boundingBox.maxY)
let gradientEnd = CGPoint(x: 0, y: boundingBox.minY)
var gradientLocations = [CGFloat]()
var gradientColors = [CGFloat]()
var cRed: CGFloat = 0
var cGreen: CGFloat = 0
var cBlue: CGFloat = 0
var cAlpha: CGFloat = 0

//Set lower bound color
gradientLocations.append(0)
var cColor = dataSet.color(atIndex: 0)
if cColor.getRed(&cRed, green: &cGreen, blue: &cBlue, alpha: &cAlpha)
{
gradientColors += [cRed, cGreen, cBlue, cAlpha]
}

//Set middle colors
guard let gradientPositions = dataSet.gradientPositions else
{
fatalError("Must set `gradientPositions if `dataSet.isDrawLineWithGradientEnabled` is true")
}

for position in gradientPositions
{
let positionLocation = CGPoint(x: 0, y: position)
.applying(matrix)
let normPositionLocation = (positionLocation.y - gradientStart.y) / (gradientEnd.y - gradientStart.y)
if (normPositionLocation < 0) {
gradientLocations.append(0)
} else if (normPositionLocation > 1) {
gradientLocations.append(1)
} else {
gradientLocations.append(normPositionLocation)
}
}

for _ in dataSet.colors
{
cColor = dataSet.color(atIndex: 0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jjatie just want to check that this line is correct. It iterates over dataSet.colors, but always takes color at index 0.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

    for i in dataSet.colors.indices
    {
        cColor = dataSet.color(atIndex: i)

if cColor.getRed(&cRed, green: &cGreen, blue: &cBlue, alpha: &cAlpha)
{
gradientColors += [cRed, cGreen, cBlue, cAlpha]
}
}

//Set upper bound color
gradientLocations.append(1)
cColor = dataSet.color(atIndex: dataSet.colors.count - 1)
if cColor.getRed(&cRed, green: &cGreen, blue: &cBlue, alpha: &cAlpha)
{
gradientColors += [cRed, cGreen, cBlue, cAlpha]
}

//Define gradient
let baseSpace = CGColorSpaceCreateDeviceRGB()
let gradient: CGGradient?
if gradientPositions.count > 1
{
gradient = CGGradient(colorSpace: baseSpace, colorComponents: &gradientColors, locations: &gradientLocations, count: gradientColors.count / 4)
} else
{
gradient = CGGradient(colorSpace: baseSpace, colorComponents: gradientColors, locations: nil, count: gradientColors.count / 4)
}

guard gradient != nil else { return }

//Draw gradient path
context.beginPath()
context.addPath(gradientPath)
context.clip()
context.drawLinearGradient(gradient!, start: gradientStart, end: gradientEnd, options: [])
}
}