UIView上的自定义圆角 [英] Custom Rounding corners on UIView

查看:197
本文介绍了UIView上的自定义圆角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我已经坚持了一段时间,在线阅读并尝试了许多不同的解决方案,但无法弄清楚我做错了什么。我想要完成的任务应该非常简单:我有一个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.

这是我到目前为止(vwView是我在屏幕上自定义视图的出口):

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;

我做错了什么?另外:这只是我的原型,因为我真的想在UITableViewCell上做这个,所以如果我需要采取不同的方法,那也可能会有所帮助。

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.

谢谢

詹姆斯

推荐答案

问题是 vwView 稍后会调整大小以适应屏幕,但您不会更新其新大小的路径。对此没有特别的微不足道的解决方案。你基本上需要使 vwView 一个自定义类(如果它还没有)并更新 layoutSubviews 中的掩码。示例:

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
    }

}

vwView 的类更改为 RoundedBorderView 并且它将维护自己的遮罩层。

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

这篇关于UIView上的自定义圆角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆