Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

ios - Custom Rounding corners on UIView

So I've been stuck on this one for awhile, read and tried many different solutions online, but can't figure out what I'm doing wrong. What I'm trying to accomplish should be very simple: I have a UIView and I want to round its bottom left and right corners so that they are clipped and not drawn.

This is what I have so far (vwView is my outlet for a custom view on screen):

var layerTest = CAShapeLayer()

var bzPath = UIBezierPath(roundedRect: vwView.bounds, byRoundingCorners: [.BottomLeft, .BottomRight], cornerRadii: CGSizeMake(10, 10) )
layerTest.path = bzPath.CGPath

vwView.layer.mask = layerTest;

What am I doing wrong? ALSO: This is just my prototype because I really want to do this on a UITableViewCell, so if there is a different approach I need to take for that, that could also be helpful.

Thanks

James

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that vwView gets resized later to fit the screen, but you don't update the path for its new size. There's no particularly trivial fix for this. You basically need to make vwView a custom class (if it's not already) and update the mask in layoutSubviews. Example:

public class RoundedBorderView: UIView {

    public var roundedCorners: UIRectCorner = [ .BottomLeft, .BottomRight ] {
        didSet { self.setNeedsLayout() }
    }

    public var cornerRadii: CGSize = CGSizeMake(10, 10) {
        didSet { self.setNeedsLayout() }
    }

    public override func layoutSubviews() {
        super.layoutSubviews()
        updateMask()
    }

    private func updateMask() {
        let mask = maskShapeLayer()
        mask.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: roundedCorners, cornerRadii: cornerRadii).CGPath
    }

    private func maskShapeLayer() -> CAShapeLayer {
        if let mask = layer.mask as? CAShapeLayer {
            return mask
        }
        let mask = CAShapeLayer()
        layer.mask = mask
        return mask
    }

}

Change the class of vwView to RoundedBorderView and it will maintain its own mask layer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...