I am using the iOS Charts library to generate some line charts with a gradient fill (below the curve) and everything is working as expected on screenenter code here
. Saving these charts by calling the charts library builtin save method works as expected for PNG and JPEG.
graphController.chartView.save(to: "chart7.png", format: .png)
but now I am looking into writing them to a PDF file and was inspired by this SO post. unfortunately the gradient isn't showing up in the PDF file, I get a solid fill instead. here is my code
func generatePdfWithFilePath(thefilePath: String, nDays: Int, renderingRect: CGRect) {
UIGraphicsBeginPDFContextToFile(thefilePath, CGRect.zero, nil)
//Start a new page.
let usLetter = CGRect(x: 0.0, y: 0.0, width: 612.0, height: 792.0)
UIGraphicsBeginPDFPageWithInfo(usLetter, nil)
// Create a view for the Graph
let graphController = LineChartController(rect: renderingRect, nDays: nDays)
if let currentContext = UIGraphicsGetCurrentContext() {
let frame = graphController.chartView.frame
graphController.chartView.draw(frame)
//graphController.chartView.layer.render(in: currentContext)
}
// Close the PDF context and write the contents out.
UIGraphicsEndPDFContext()
}
if i uncomment the line with layer.render
instead, the chart is saved properly with gradient fill.
i was hoping the draw()
method will save my chart in a way that would make it scalable (vs a bitmap) since i am looking to integrate it later in another document and want to play around with the chart size . the gradient is the result of this
//set a gradient fill under the line
let gradientColors = [ChartColorTemplates.colorFromString("#00ff0000").cgColor,
ChartColorTemplates.colorFromString("#ffff0000").cgColor]
let gradient = CGGradient(colorsSpace: nil, colors: gradientColors as CFArray, locations: nil)!
set.fillAlpha = 0.75
set.fill = Fill(linearGradient: gradient, angle: 90) //.linearGradient(gradient, angle: 90)
set.drawFilledEnabled = true // set to false to disable gradient fill
maybe my understanding of how draw()
works is wrong... any help will be appreciated.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…