2017-10-23 4 views
0

원형 차트를 출력하는 신속한 클래스가 있습니다. UIGraphicsGetCurrentContext가 그리기 메서드 외부에서 nil을 반환하기 때문에 drawRect 메서드에서 그리기 논리를 제거하고 싶습니다. 원형 차트를 그리는 방법을 변경해야합니다. 보기,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) 

주 당신이 (매우 자주 차트를 업데이트해야하는 경우 초당 여러 번),이 솔루션은 성능 저하를 초래할 수 있습니다. 그 이유는 이미지 생성이 순수 렌더링보다 시간이 오래 걸리기 때문입니다.