[英]Border in circle UIView using Swift
I'm trying to make an UIView with border but I only make it appear in UIView not only on the circle. 我正在尝试用边框制作UIView,但我只是让它出现在UIView中,而不仅仅是在圆圈上。
In the brown circle I want a black border, but it has to be in the circle not in the UIView. 在棕色圆圈中,我想要一个黑色边框,但它必须在UIView中不在圆圈中。
I have a class called Ball where I draw the circle. 我有一个名为Ball的课,我画圆圈。
class Ball: UIView {
var desiredColour = UIColor.blueColor()
struct mine {
static var p = UIBezierPath(ovalInRect: CGRectMake(0,0,118,117))
}
override func drawRect(rect: CGRect) {
// Drawing code
desiredColour.setFill()
mine.p.fill()
}
func colour() {
var randColor: UIColor = Colors.randomColor()
Colors.ballColor = randColor
Colors.colorPosition = find(Colors.arrayColors, randColor)!
desiredColour = randColor
self.setNeedsDisplay()
}
}
I used the code: 我用过代码:
override func drawRect(rect: CGRect) {
// Drawing code
desiredColour.setFill()
let desiredBorderColor = UIColor.blackColor()
desiredBorderColor.setStroke()
self.layer.borderWidth = 3.0
self.layer.cornerRadius = self.frame.size.width/2.0
mine.p.fill()
mine.p.stroke()
}
but i get a border with a little cuts: 但我得到一个小切口的边框:
Try calling this function by passing you view as a parameter 尝试通过将视图作为参数传递来调用此函数
func drawBlackBorder(view: UIView) {
view.layer.borderColor = UIColor.blackColor
view.layer.borderWidth = 1.0
view.layer.cornerRadius = view.frame.size.width/2.0
view.backgroundColor = UIColor.brownColor
}
override func drawRect(rect: CGRect) {
// Drawing code
desiredColour.setFill()
let desiredBorderColor = UIColor.blackColor()
desiredBorderColor.setStroke()
mine.p.lineWidth = 2.0 //set to whatever you want
mine.p.fill()
mine.p.stroke()
}
But note that for border to work you need to have some space around you circle. 但请注意,对于工作边界,您需要在您周围留出一些空间。
Do the following. 请执行下列操作。 Declare
myBorderWidth
(of type CGFloat
) property and then change 声明
myBorderWidth
(类型为CGFloat
)属性,然后更改
static var p = UIBezierPath(ovalInRect: CGRectMake(0,0,118,117))
to 至
static var p = UIBezierPath(ovalInRect: CGRectMake(myBorderWidth/2,myBorderWidth/2,118-myBorderWidth/2,117-myBorderWidth/2))
You can also remove repetitions of myBorderWidth/2
by declaring it as a property. 您还可以通过将
myBorderWidth/2
声明为属性来删除它们。
No need to modify layer, just set up UIBezierPath with proper insets depending on border thickness and set it's width (tested on Swift 4.2): 无需修改图层,只需根据边框厚度设置具有适当插图的UIBezierPath并设置其宽度(在Swift 4.2上测试):
var fillColor: UIColor //circle color
var strokeColor: UIColor //border color
var borderWidth: CGFloat //border width
override func draw(_ rect: CGRect) {
fillColor.setFill()
strokeColor.setStroke()
let circlePath = UIBezierPath(ovalIn: CGRect(x: borderWidth, y: borderWidth, width: rect.width - borderWidth*2, height: rect.height - borderWidth*2))
circlePath.lineWidth = borderWidth
circlePath.stroke()
circlePath.fill()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.