【问题标题】:Subview added but lost part of drawing?添加了子视图但丢失了部分绘图?
【发布时间】:2015-02-06 07:09:38
【问题描述】:

我想绘制一个带有“添加”表面和 UIBlurEffect 背景的自定义 UIButton。我重写了表面视图中的drawRect方法:

class SurfaceAdd: UIView {
    override func drawRect(rect: CGRect) {
    var currentContext = UIGraphicsGetCurrentContext()
    CGContextSaveGState(currentContext)
    //draw circle
    CGContextAddEllipseInRect(currentContext, self.bounds)
    CGContextSetRGBFillColor(currentContext, 0, 0, 0, 0.2)
    CGContextFillPath(currentContext)

    CGContextRestoreGState(currentContext)
    CGContextSetLineCap(currentContext, kCGLineCapRound)
    CGContextSetLineWidth(currentContext, 8)
    CGContextSetRGBStrokeColor(currentContext, 1, 1, 1, 1)
    let height = self.frame.size.height
    let width = self.frame.size.width
    //draw +
    CGContextSetShadow(currentContext, CGSizeMake(1, 1), 0)
    CGContextMoveToPoint(currentContext, width*0.25, height/2)
    CGContextAddLineToPoint(currentContext, width*0.75, height/2)
    CGContextMoveToPoint(currentContext, width/2, height*0.25)
    CGContextAddLineToPoint(currentContext, width/2, height*0.75)
    CGContextStrokePath(currentContext)
}

当我将它用作情节提要中的单独 UIView 时,它看起来不错。
但是,当我将其添加为自定义 UIButton 的子视图,然后在情节提要中添加自定义按钮时,椭圆消失并且背景变为黑色。

相关代码在CustomButton这里:

var iconAdd:SurfaceAdd!
override init() {
    super.init()
    setup()
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}
private func setup(){
    self.iconAdd = SurfaceAdd(frame: self.bounds)
    self.addSubview(iconAdd)
    self.setNeedsDisplay()
}

我怎么了?

ps:我选择使用约束进行布局,现在我只是使用框架进行测试。所以,请不要提及错误。

【问题讨论】:

    标签: ios uiview uibutton core-graphics drawrect


    【解决方案1】:

    在将其添加到另一个视图之前,您应该将其背景色设置为透明色,否则,它看起来就像是黑色背景色。

    self.iconAdd.backgroundColor = UIColor.clearColor()
    

    【讨论】:

    • 没错,但奇怪的是,为什么一个视图的默认背景色是黑色
    • 或者您可以将其opaque 设置为false,默认为YES。不透明的视图必须填满它们的整个边界,否则结果是不确定的。 drawRect: 中的活动 CGContext 不会被清除并且可能有非零像素,请参阅更多here
    • 我认为我必须将 opaque 设置为 false 才能进行下一步。 @gabbler
    • 你的下一步是什么?
    • 插入 UIBlurEffect 背景视图@gabbler
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多