【问题标题】:Rotation And Gradient in CoreGraphics and contextCoreGraphics 和上下文中的旋转和渐变
【发布时间】:2014-11-02 16:35:15
【问题描述】:

我肯定错过了 Core Graphics 上下文的某些部分,无法自己清除。 这是我在 Xcode Playground 中的代码

import UIKit
class MyView08 : UIView {

    override func drawRect(rect: CGRect) {
        let cornerRaduis : CGFloat = 20
        let pathRect = CGRectInset(self.bounds, 20, 20)
        let rectanglePath = UIBezierPath(roundedRect: pathRect, cornerRadius: cornerRaduis)
        var context = UIGraphicsGetCurrentContext()
        CGContextSaveGState(context)
        rotate(rectanglePath, context: context)
        CGContextRestoreGState(context)

        context = UIGraphicsGetCurrentContext()
        CGContextSaveGState(context)
    //  drawGrad(rectanglePath, context: context)
        CGContextRestoreGState(context)
    }

    func rotate(rectanglePath : UIBezierPath, context : CGContext) {
        let rotation = CGAffineTransformMakeRotation(CGFloat(M_PI) / 4.0)
        CGContextConcatCTM(context, rotation)
        UIColor.greenColor().setFill()
        rectanglePath.fill()

    }

    func drawGrad (rectanglePath : UIBezierPath, context : CGContext) {
        let startColor = UIColor.redColor()
        let endColor = UIColor.greenColor()
        let gradientColors : CFArray = [startColor.CGColor, endColor.CGColor]
        let gradientLocations : [CGFloat] = [0.0, 1.0]
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let gradient = CGGradientCreateWithColors(colorSpace, gradientColors, gradientLocations)
        let topPoint = CGPointMake(self.bounds.size.width / 2, 20)
        let bottomPoint = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height - 20)

        rectanglePath.addClip()
        CGContextDrawLinearGradient(context, gradient, bottomPoint, topPoint, 0)
    }
}

let myViewRect = CGRect(x: 0, y: 0, width: 300, height: 300)
let myView = MyView08(frame: myViewRect)

如果我取消注释这一行

drawGrad(rectanglePath, context: context)

一切都变糟了,Xcode 尝试执行代码近 2 千次,然后就失败了。 我正在尝试旋转矩形并绘制渐变。

【问题讨论】:

    标签: ios xcode swift core-graphics swift-playground


    【解决方案1】:

    您正在经历无限递归。我不知道为什么,但这与您的测试程序有关。问题在于你是如何测试的——而不是你的代码。 不要在操场上测试这种代码。操场不是现实。

    (我可以概括地说,永远不要使用游乐场。它们是魔鬼的作品。但我不会这样做。哎呀,我说出来了吗?)

    无论如何,我将您的代码复制并粘贴到了一个新的应用项目中(并且我取消了 drawGrad 行的注释),它运行良好,没有您描述的那种递归问题。

    请注意,您需要将视图放入界面中才能执行任何操作。为了做到这一点,我添加了这一行:

        self.view.addSubview(myView)
    

    除此之外,我的代码和你的相同,没有问题。

    【讨论】:

    • 那么我做对了吗?保存上下文、进行旋转、恢复上下文、保存上下文、制作渐变、恢复上下文?
    • 我不知道你所说的“正确”是什么意思。这取决于你想要做什么。但从纯粹形式的角度来看,你肯定没有做错任何事。走出操场,开始使用应用程序作为测试平台;至少,您将能够看到您的代码是否为您提供了您期望的实际结果。我怀疑它是,但这是一个完全不同的问题!现在,在操场上工作,你甚至都没有体验到现实——你根本无法测试。离开那里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多