我有一个在视图内部绘制圆的类。我知道如何填充圆,并且我知道如何使圆仅是轮廓。
我想用条纹填充圆,以使下面的圆看起来像轮廓一样,带有红色和白色的交替条纹,但是白色条纹在白色背景下只能看起来是白色,因为它们表示缺少颜色填充。
import UIKit
@IBDesignable
class Circle: UIView{
override func draw(_ rect: CGRect){
let radius = bounds.width / 4
let centerY = (bounds.maxY - bounds.minY) / 2
let centerX = (bounds.maxX - bounds.minX)/2
let centerPoint = CGPoint(x: centerX, y: centerY)
drawCircle(radius: radius, center: centerPoint)
}
private func drawCircle(radius: CGFloat, center: CGPoint){
let path = UIBezierPath()
path.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: 2*CGFloat.pi, clockwise: true)
path.close()
UIColor.red.set()
path.lineWidth = 5.0
path.stroke()
//path.fill()
}
}
使用clipping regions的解决方案
import UIKit
@IBDesignable
class Circle: UIView{
override func draw(_ rect: CGRect){
let radius = bounds.width / 4
let centerY = (bounds.maxY - bounds.minY) / 2
let centerX = (bounds.maxX - bounds.minX)/2
let centerPoint = CGPoint(x: centerX, y: centerY)
drawCircle(radius: radius, center: centerPoint)
}
private func drawCircle(radius: CGFloat, center: CGPoint){
let path = UIBezierPath()
path.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: 2*CGFloat.pi, clockwise: true)
path.close()
UIColor.red.set()
path.lineWidth = 5.0
//////////////////////////The part the produces stripes ////////////////////
let bounds = path.bounds
let stripes = UIBezierPath()
for x in stride(from: 0, to: bounds.size.width, by: 20){
stripes.move(to: CGPoint(x: bounds.origin.x + x, y: bounds.origin.y ))
stripes.addLine(to: CGPoint(x: bounds.origin.x + x, y: bounds.origin.y + bounds.size.height ))
}
stripes.lineWidth = 10
path.addClip()
stripes.stroke()
//////////////////////////////////////////////////////////////////////////
path.stroke()
}
}
使用裁剪区域的解决方案
import UIKit
@IBDesignable
class Circle: UIView{
override func draw(_ rect: CGRect){
let radius = bounds.width / 4
let centerY = (bounds.maxY - bounds.minY) / 2
let centerX = (bounds.maxX - bounds.minX)/2
let centerPoint = CGPoint(x: centerX, y: centerY)
drawCircle(radius: radius, center: centerPoint)
}
private func drawCircle(radius: CGFloat, center: CGPoint){
let path = UIBezierPath()
path.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: 2*CGFloat.pi, clockwise: true)
path.close()
UIColor.red.set()
path.lineWidth = 5.0
//////////////////////////The part the produces stripes ////////////////////
let bounds = path.bounds
let stripes = UIBezierPath()
for x in stride(from: 0, to: bounds.size.width, by: 20){
stripes.move(to: CGPoint(x: bounds.origin.x + x, y: bounds.origin.y ))
stripes.addLine(to: CGPoint(x: bounds.origin.x + x, y: bounds.origin.y + bounds.size.height ))
}
stripes.lineWidth = 10
path.addClip()
stripes.stroke()
//////////////////////////////////////////////////////////////////////////
path.stroke()
}
}