在这张图片中我需要绘制矩形的圆角
我写了这段代码
class RoundedRectUsingPath @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val roundCorner = 10f
private val paint = Paint().apply {
color = Color.RED
isAntiAlias = true
pathEffect = CornerPathEffect(roundCorner)
setShadowLayer(10f, -2f, 2f, android.graphics.Color.BLACK)
}
private var path = Path()
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
val left = 10f
val top = 0f
val avatarRadius = 30f
val shapeBounds = RectF(left, top+20, left + width - 40, top + height -20)
val leftCutoutPoint = PointF(left, shapeBounds.bottom/2)
val rightCutOutBounds = PointF(shapeBounds.right, shapeBounds.bottom/2)
val leftAvatarBounds = fromCircle(center = leftCutoutPoint, radius = avatarRadius)
val rightAvatarBounds = fromCircle(center = rightCutOutBounds, radius = avatarRadius)
path = Path().apply {
moveTo(shapeBounds.left, shapeBounds.top)
arcTo(leftAvatarBounds, -90f, 180f, false)
lineTo(shapeBounds.bottomLeft.x, shapeBounds.bottomLeft.y)
lineTo(shapeBounds.bottomRight.x, shapeBounds.bottomRight.y)
arcTo(rightAvatarBounds, 90f, 180f, false)
lineTo(shapeBounds.topRight.x, shapeBounds.topRight.y)
close()
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawPath(path, paint)
}
fun fromLTRB(left: Float, top: Float, right: Float, bottom: Float) =
RectF(left, top, right, bottom)
fun fromLTWH(left: Float, top: Float, width: Float, height: Float) =
fromLTRB(left, top, left + width, top + height)
fun fromCircle(center: PointF, radius: Float) =
fromCenter(
center = center,
width = radius,
height = radius
)
fun fromCenter(center: PointF, width: Float, height: Float) =
fromLTRB(
center.x - width,
center.y - height,
center.x + width,
center.y + height
)
fun RectF.inflate(delta: Float): RectF {
return fromLTRB(
left - delta,
top - delta,
right + delta,
bottom + delta
)
}
}
但是当我使用圆角为 10f 的
pathEffect = CornerPathEffect(roundCorner).
时,图像会变成这样
在这里您可以看到切口形状发生变化,这是意料之外的。预期是带有完美切口的圆角,我尝试了许多不同的方法来实现这一点,但没有一个对我有用。
看来您有两个问题:
这对我来说看起来很糟糕。也许有人会有更直接的解决方案,但我建议您看一下 MaterialShapeDrawable 来绘制您的形状。
这里是有关MaterialShapeDrawable的更多信息。看起来“票”形状就是您要找的。