我可以在UIImage中使用更多切片线吗?

时间:2016-10-25 20:28:40

标签: ios xcode uiimage nine-patch cashapelayer

我想动态更改矩形比例,但保留半圆的比例。半圆应与底部对齐并水平居中:

enter image description here

如何在Xcode中为UIImage添加更多切片线?

我已经在Nine Patch编辑器中为Android做了我想要的东西,但它与iOS不兼容。

enter image description here

1 个答案:

答案 0 :(得分:1)

没有办法像你想要的那样拉伸UIImage,但你可以通过编程方式进行。我在里面用 CAShapeLayer 实现了一个自定义的UIView:

import UIKit

class CustomShapeView: UIView {

    private let shapeLayer = CAShapeLayer()
    var radius = CGFloat(0)
    var shadowRadius = CGFloat(5)

    override func draw(_ rect: CGRect) {
        backgroundColor = UIColor.clear

        shapeLayer.frame = self.bounds
        shapeLayer.fillColor = UIColor.white.cgColor
        shapeLayer.path = createShapePath().cgPath

        shapeLayer.shadowPath = shapeLayer.path
        shapeLayer.shadowColor = UIColor.black.cgColor
        shapeLayer.shadowOffset = .zero
        shapeLayer.shadowRadius = shadowRadius
        shapeLayer.shadowOpacity = 0.5

        layer.addSublayer(shapeLayer)
    }

    func createShapePath () -> UIBezierPath {
        let path = UIBezierPath()

        let w = self.bounds.size.width
        let h = self.bounds.size.height
        let circleLever: CGFloat = radius * 0.552

        path.move(to: CGPoint(x: w/2 - radius, y: h))
        path.addLine(to: CGPoint(x: 0, y: h))
        path.addLine(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: w, y: 0))
        path.addLine(to: CGPoint(x: w, y: h))
        path.addLine(to: CGPoint(x: w/2 + radius, y: h))

        path.addCurve(to: CGPoint(x: w/2, y: h - radius), controlPoint1:CGPoint(x: w/2 + radius, y: h - circleLever), controlPoint2:CGPoint(x: w/2 + circleLever, y: h - radius))
        path.addCurve(to: CGPoint(x: w/2 - radius, y: h), controlPoint1:CGPoint(x: w/2 - circleLever, y: h - radius), controlPoint2:CGPoint(x: w/2 - radius, y: h - circleLever))
        path.close()
        path.move(to: CGPoint(x: w/2 - radius, y: h))

        return path
    }        
}

您可以设置所需的任何大小和任意半径,圆的中心将始终位于视图的下边缘。如果您愿意,也可以更改shadowRadius

在Interface Builder中设置:

enter image description here

<强>结果:

enter image description here