无法描边()UIBezierPath

时间:2014-09-14 00:11:21

标签: ios swift uibezierpath

我希望创建一个完美的圆角矩形(圆形)并在屏幕上绘制它。我在操场上测试了我的代码,它成功地绘制了UIBezierPath。但是,它并没有成功地在iOS模拟器中绘制它。这是我一直在研究的代码:

    class Circles {

        //Defining the rounded rect (Circle)
        func roundRect(radius: CGFloat, angle: CGFloat) -> UIBezierPath {

            //Creating the rounded the rectangle (Circle)
            var roundedRect = UIBezierPath()
            roundedRect.addArcWithCenter(CGPointZero, radius: radius,
                startAngle: 0, endAngle: angle ,
                clockwise: true)

            return roundedRect
        }


        //Drawing the Bezier Path (Circle)
        func drawRect(rect: UIBezierPath){

            rect.moveToPoint(self.point)
            UIColor.blackColor().setStroke()
            rect.stroke()
        }

        //Giving the rounded rect (Circle) it's position
        var point = CGPointMake(500, 500)
    }
    //Giving the rounded rect (Circle) it's size
    var newRect = Circles().roundRect(200.0, angle: 7)

    //Drawing the rounded rect (Circle)
    Circles().drawRect(newRect)

我在几年前看过其他一些类似问题的帖子,但是他们使用的是Objective-C,我试过翻译,但它没有任何用处。我还尝试了其他几种在屏幕上绘制路径的方法,但遗憾的是,它没有用。我测试它以确保函数正在使用println语句,问题是我不知道为什么笔画没有激活。感谢阅读,-Zach。

这是使用Mike所说的更新版本:

class CircleView: UIView {
override func drawRect(rect: CGRect) {

    // Creating the rectangle's size
    var newRect = Circles().roundRect(200.0, angle: 7)

    //Drawing the rectangle
    Circles().drawRect(newRect)
}


//Holding all to do with the circle
class Circles {

    //Defining the rounded rect (Circle)
    func roundRect(radius: CGFloat, angle: CGFloat) -> UIBezierPath {

        //Creating the rounded rect (Circle)
        var roundedRect = UIBezierPath()
        roundedRect.addArcWithCenter(CGPointZero, radius: radius,
            startAngle: 0, endAngle: angle ,
            clockwise: true)

        return roundedRect
    }


    //Drawing the Bezier Path (Circle)
    func drawRect(rect: UIBezierPath){

        rect.moveToPoint(self.point)
        UIColor.blackColor().setStroke()
        UIColor.blackColor().setFill()
        rect.stroke()
        rect.fill()
    }

    //Giving the rounded rect (Circle) it's position
    var point = CGPointMake(500, 500)
    }

}



class ViewController: UIViewController {



override func viewDidLoad() {
super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //Generating the background
    self.view.backgroundColor = UIColor(patternImage: UIImage(named: "normalpaper.jpg"))

    let circleView = CircleView(frame: self.view.bounds)
    self.view.addSubview(circleView)

}

1 个答案:

答案 0 :(得分:1)

正如您在评论中提到的那样,您是从drawRect的{​​{1}}功能调用UIViewController。你没有有效的绘图上下文,所以这不起作用。

最简单的方法是创建一个viewDidLoad子类,其中包含UIView函数,调用drawRect并将其添加为Circle().drawRect(...)的子视图s UIViewController

以下是此示例:

注意:我通过设置view使自定义视图变得透明,以便您在评论中提到的背景显示出来。

circleView.opaque = false

注意:如果您要进行自定义绘图,我强烈建议您阅读Drawing and Printing Guide for iOS。它将教你完成所需的所有基础知识。