[英]Drawing a circle cutout in UIView (Swift)
I'm trying to make a UIView that is a black color with a transparent circle in the middle. 我正在尝试制作一个黑色的UIView,中间有一个透明的圆圈。 My code so far:
我的代码到目前为止:
class MyView: UIView {
override var frame: CGRect {
didSet {
setNeedsDisplay()
}
}
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
for subview in subviews as [UIView] {
if !subview.hidden && subview.alpha > 0 && subview.userInteractionEnabled && subview.pointInside(convertPoint(point, toView: subview), withEvent: event) {
return true
}
}
return false
}
override func drawRect(rect: CGRect) {
let contextRef = UIGraphicsGetCurrentContext()
let circleRect = CGRect(x: 67, y: 214, width: 240, height: 240)
CGContextAddEllipseInRect(contextRef, circleRect)
CGContextClip(contextRef)
CGContextSetRGBFillColor(contextRef, 0.0, 0.0, 0.0, 0.6)
CGContextFillRect(contextRef, rect)
}
}
In my UIViewController I init the view like so: 在我的UIViewController中,我像这样初始化视图:
let blackView = MyView()
blackView.frame = view.frame
view.addSubview(blackView)
I just have an entirely black screen with no cutout. 我只有一个全黑的屏幕,没有切口。 What am I doing wrong here?
我在这做错了什么? An pointers would be greatly appreciated!
指针将不胜感激! thanks.
谢谢。
EDIT: I need to be doing this in drawRect if possible and not adding a layer as I am forwarding touch events using pointsInside. 编辑:如果可能的话,我需要在drawRect中执行此操作,并且不添加图层,因为我正在使用pointsInside转发触摸事件。
Instead of overriding drawRect
, use CAShapeLayer
as mask: 代替覆盖
drawRect
,使用CAShapeLayer
作为遮罩:
let blackView = UIView()
blackView.frame = view.frame
let mask = CAShapeLayer()
mask.path = UIBezierPath(ovalInRect: CGRectInset(view.frame, 30, 30)).CGPath
blackView.layer.mask = mask
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.