为UIView添加边框/阴影效果

时间:2017-08-24 17:14:37

标签: swift core-graphics

我设法用以下代码绘制了一个讲话泡泡:

override func draw(_ rect: CGRect) {

    let rounding:CGFloat = rect.width * 0.01

    //Draw the main frame
    let bubbleFrame = CGRect(x: 0, y: 0, width: rect.width, height: rect.height * 6 / 7)

    let bubblePath = UIBezierPath(roundedRect: bubbleFrame,
                                  byRoundingCorners: UIRectCorner.allCorners,
                                  cornerRadii: CGSize(width: rounding, height: rounding))

    //Color the bubbleFrame
    color.setStroke()
    color.setFill()
    bubblePath.stroke()
    bubblePath.fill()

    //Add the point
    let context = UIGraphicsGetCurrentContext()

    //Start the line
    context!.beginPath()
    context?.move(to: CGPoint(x: bubbleFrame.minX + bubbleFrame.width * 1/2 - 8, y: bubbleFrame.maxY))

    //Draw a rounded point
    context?.addArc(tangent1End: CGPoint(x: rect.maxX * 1/2 + 4, y: rect.maxY), tangent2End: CGPoint(x:bubbleFrame.maxX , y:  bubbleFrame.minY), radius: 0)

    //Close the line
    context?.addLine(to: CGPoint(x: bubbleFrame.minX + bubbleFrame.width * 1/2 + 16, y: bubbleFrame.maxY))

    context!.closePath()

    //fill the color
    context?.setFillColor(UIColor.white.cgColor)
    context?.fillPath()

   context?.saveGState()
    context?.setShadow(offset:CGSize(width: 1, height: 1), blur: 2, color: UIColor.gray.cgColor)
    UIColor.gray.setStroke()
    bubblePath.lineWidth = 0.5
    bubblePath.stroke()
    context?.restoreGState()

}

此刻,它看起来像这样: enter image description here

我似乎无法在讲话泡泡中添加阴影效果。我希望底部的点具有阴影效果,而不仅仅是上面的矩形。此外,顶部的阴影/边框太厚。这是我希望实现的最终结果:

enter image description here

0 个答案:

没有答案