2017-10-23 24 views
0

私は円グラフを出力する迅速なクラスを持っています。私はdrawRectメソッドから抽象ロジックを取り出す必要があります。UIGraphicsGetCurrentContextは描画メソッドの外側でnilを返すので、表示、UIGraphicsGetCurrentContextと同等の描画メソッド

これを行う適切な方法は何ですか?私のPieChartクラスは次のように見えます。

override func draw(_ rect: CGRect) { 
     let context: CGContext = UIGraphicsGetCurrentContext()! 
     drawLinearGradient(context) 
     drawCenterCircle(context) 
     let circle: CAShapeLayer = drawStroke() 
     let pathAnimation = CABasicAnimation(keyPath: "strokeEnd") 
     pathAnimation.duration = percentage 
     pathAnimation.toValue = percentage 
     pathAnimation.isRemovedOnCompletion = rendered ? false : (percentageLabel > 20 ? false : true) 
     pathAnimation.isAdditive = true 
     pathAnimation.fillMode = kCAFillModeForwards 
     circle.add(pathAnimation, forKey: "strokeEnd") 
} 

private func drawLinearGradient(_ context: CGContext) { 
    let circlePoint: CGRect = CGRect(x: 0, y: 0, 
            width: bounds.size.width, height: bounds.size.height) 
    context.addEllipse(in: circlePoint) 
    context.clip() 

    let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB() 
    let colorArray = [colors.0.cgColor, colors.1.cgColor] 
    let colorLocations: [CGFloat] = [0.0, 1.0] 
    let gradient = CGGradient(colorsSpace: colorSpace, colors: colorArray as CFArray, locations: colorLocations) 

    let startPoint = CGPoint.zero 
    let endPoint = CGPoint(x: 0, y: self.bounds.height) 
    context.drawLinearGradient(gradient!, 
           start: startPoint, 
           end: endPoint, 
           options: CGGradientDrawingOptions.drawsAfterEndLocation) 


} 

private func drawCenterCircle(_ context: CGContext) { 
    let circlePoint: CGRect = CGRect(x: arcWidth, y: arcWidth, 
            width: bounds.size.width-arcWidth*2, 
            height: bounds.size.height-arcWidth*2) 

    context.addEllipse(in: circlePoint) 
    UIColor.white.setFill() 
    context.fillPath() 
} 

private func drawStroke() -> CAShapeLayer { 
    let circle = CAShapeLayer() 
    self.layer.addSublayer(circle) 
    return circle 
} 
+0

あなたはすでに方法を試しましたか?はいの場合は、動作しなかったものをより具体的に記述してください。 – AlexWoe89

+0

'draw(rect:)'メソッド*は、それ自身のコンテキストを持っています。あなたは新しいものを作成しようとしましたか? – dfd

+0

何とかdrawRectメソッドがiOS 11で何度も訪れましたが(iOS 10と9では何の問題もありません)、このロジックをdrawRect以外のどこかに移動する必要があります。 – user2628268

答えて

1

あなたは円グラフを含むUIImageを生成するようにコードを変更し、画像ビュー内でその画像を配置することができます:あなたは非常に頻繁にチャートを更新する必要がある場合ということ

UIGraphicsBeginImageContext(size) 
let context = UIGraphicsGetCurrentContext() 
// ... here goes your drawing code, just as before 
let pieImage = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 
let pieView = UIImageView(image: pieImage) 

は注意(毎秒複数回)、このソリューションは、画像の作成に純粋なレンダリングより少し時間がかかるため、パフォーマンスの低下を招く可能性があります。

関連する問題