角半径图像Swift

时间:2018-07-20 14:44:19

标签: ios iphone swift uiimageview

我正在尝试制作此拐角半径图像...它与图像的形状不完全相同..任何简单的答案,而不是尝试宽度和高度的随机数? 非常感谢

enter image description here

 let rectShape = CAShapeLayer()
 rectShape.bounds = self.mainImg.frame
 rectShape.position = self.mainImg.center
 rectShape.path = UIBezierPath(roundedRect: self.mainImg.bounds, byRoundingCorners: [.bottomLeft , .bottomRight ], cornerRadii: CGSize(width: 50, height: 4)).cgPath

2 个答案:

答案 0 :(得分:3)

您可以使用QuadCurve获得所需的设计。

这里是一个Swift @IBDesignable类,可让您在Storyboard / Interface Builder中指定图像和舍入的“高度”:

@IBDesignable

class RoundedBottomImageView: UIView {

    var imageView: UIImageView!

    @IBInspectable var image: UIImage? {
        didSet { self.imageView.image = image }
    }

    @IBInspectable var roundingValue: CGFloat = 0.0 {
        didSet {
            self.setNeedsLayout()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        doMyInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        doMyInit()
    }

    func doMyInit() {

        imageView = UIImageView()
        imageView.backgroundColor = UIColor.red
        imageView.contentMode = UIViewContentMode.scaleAspectFill
        addSubview(imageView)

    }

    override func layoutSubviews() {
        super.layoutSubviews()
        imageView.frame = self.bounds

        let rect = self.bounds
        let y:CGFloat = rect.size.height - roundingValue
        let curveTo:CGFloat = rect.size.height

        let myBezier = UIBezierPath()
        myBezier.move(to: CGPoint(x: 0, y: y))
        myBezier.addQuadCurve(to: CGPoint(x: rect.width, y: y), controlPoint: CGPoint(x: rect.width / 2, y: curveTo))
        myBezier.addLine(to: CGPoint(x: rect.width, y: 0))
        myBezier.addLine(to: CGPoint(x: 0, y: 0))
        myBezier.close()

        let maskForPath = CAShapeLayer()
        maskForPath.path = myBezier.cgPath
        layer.mask = maskForPath

    }

}

使用300 x 200图片视图的结果,四舍五入设置为40

enter image description here

答案 1 :(得分:0)

您可以尝试使用#sidecolor { position: absolute; right: 0; top: 0; width: 10%; height: 100%; background-color (...); padding: 10% 10%; box-sizing: border-box; } 扩展名。

UIView

并在extension UIView { func setBottomCurve(){ let offset = CGFloat(self.frame.size.height + self.frame.size.height/1.8) let bounds = self.bounds let rectBounds = CGRect(x: bounds.origin.x, y: bounds.origin.y , width: bounds.size.width, height: bounds.size.height / 2) let rectPath = UIBezierPath(rect: rectBounds) let ovalBounds = CGRect(x: bounds.origin.x - offset / 2, y: bounds.origin.y , width: bounds.size.width + offset, height: bounds.size.height) let ovalPath = UIBezierPath(ovalIn: ovalBounds) rectPath.append(ovalPath) let maskLayer = CAShapeLayer() maskLayer.frame = bounds maskLayer.path = rectPath.cgPath self.layer.mask = maskLayer } } 中使用它,就像可以获取UIImageView实际框架的方法一样。

用法:

viewWillAppear