使用UIBezierPath在Swift中绘制椭圆

问题描述 投票:8回答:3

我有一个UIViewController,我想在屏幕上画一个椭圆,从CGPoint(x:160,y:160)开始,宽度:240,高度:320。我怎么能在swift中做到这一点?我非常感谢任何帮助。

swift ios8 xcode6 uibezierpath
3个回答
19
投票

我相信这就是你要求的:

var ovalPath = UIBezierPath(ovalInRect: CGRectMake(160, 160, 240, 320))
UIColor.grayColor().setFill()
ovalPath.fill()

对于复杂的形状,我建议检查PaintCode。当您在屏幕上绘制形状时,它会为您创建快速代码(过去,它为我节省了大量时间)。

编辑:

import Foundation
import UIKit

class CustomOval: UView {

    override func drawRect(rect: CGRect)
    {
            var ovalPath = UIBezierPath(ovalInRect: CGRectMake(0, 0, 240, 320))
            UIColor.grayColor().setFill()
            ovalPath.fill()
    }

}

然后 :

var exampleView = CustomOval()

然后用约束等定位它。

斯威夫特4

var ovalPath = UIBezierPath(ovalIn: CGRect(x: 160, y: 160, width: 240, height: 320))
UIColor.gray.setFill()
ovalPath.fill()

4
投票

在Custom UIView中的override func drawRect(rect:CGRect)中编写此代码,然后根据需要进行编辑。

override func drawRect(rect: CGRect) {
    let ellipsePath = UIBezierPath(ovalInRect: CGRectMake(100, 100, 100, 200))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = ellipsePath.CGPath
    shapeLayer.fillColor = UIColor.clearColor().CGColor
    shapeLayer.strokeColor = UIColor.blueColor().CGColor
    shapeLayer.lineWidth = 5.0

    self.layer.addSublayer(shapeLayer)
}

0
投票
let shapeLayer = CAShapeLayer()
shapeLayer.path = ovalPath.cgPath 
shapeLayer.fillColor = UIColor.clear.cgColor 
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.lineWidth = 5.0
self.layer.addSublayer(shapeLayer)
© www.soinside.com 2019 - 2024. All rights reserved.