Swift - UIView大小动画中的渐变质量差

时间:2016-04-22 19:19:29

标签: ios objective-c swift uiview uiviewanimation

我有以下结构:

  • 主视图包含subview1; subview1使用约束
  • 进行布局
  • subview1包含subview2; subview2也有约束,我需要设置subview2的大小动画
  • 在subview2中我调用CGContextDrawRadialGradient绘制一个带渐变的圆圈

subview1中的代码是:

    let circle = GradientCircle(frame: CGRect(origin: CGPointZero, size: frame.size), withColor: color)
    addSubview(circle)

    circle.centerXAnchor.constraintEqualToAnchor(centerXAnchor).active = true
    circle.centerYAnchor.constraintEqualToAnchor(centerYAnchor).active = true
    let widthConstraint = circle.widthAnchor.constraintEqualToConstant(frame.width * 3)
    let heightConstraint = circle.heightAnchor.constraintEqualToConstant(frame.width * 3)

    circle.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activateConstraints([heightConstraint, widthConstraint])
    layoutIfNeeded()

    UIView.animateWithDuration(3.0, delay: 0, options: [.Repeat], animations: {
        widthConstraint.constant = 2
        heightConstraint.constant = 2
        self.layoutIfNeeded()
        }, completion: nil)

这是一个显示问题所在的gif:http://i.stack.imgur.com/LWP7d.gif

为什么会出现质量下降的问题以及如何解决?显然,我是斯威夫特的新人,我不完全理解整个布局和动画的事情,所以请尽可能帮助,它会让我疯狂地疯狂:)

编辑:

这里是GradientCircle类(在上面的描述中是subview2),可能问题在于如何绘制渐变:

class GradientCircle : UIView {

var color: UIColor

init(frame: CGRect, withColor: UIColor) {

    color = withColor

    super.init(frame: frame)

    backgroundColor = UIColor.clearColor()

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func drawRect(rect: CGRect) {

    let context = UIGraphicsGetCurrentContext()

    let locations: [CGFloat] = [0.0, 1.0]
    let colorspace = CGColorSpaceCreateDeviceRGB()
    let colors = [color.CGColor, GraphicsUtils.darkGrayColor().CGColor]
    let gradient = CGGradientCreateWithColors(colorspace, colors, locations)

    let startPoint = CGPoint(x: rect.width / 2, y: rect.height / 2)
    let endPoint = CGPoint(x: rect.width / 2, y: rect.height / 2)
    let startRadius: CGFloat = 0
    let endRadius: CGFloat = rect.width / 2

    CGContextClearRect(context, rect)
    CGContextDrawRadialGradient(context, gradient, startPoint, startRadius, endPoint, endRadius, CGGradientDrawingOptions.DrawsAfterEndLocation)
}   

0 个答案:

没有答案