我需要帮助在画布上绘制阴影矩形(对角线)。 现在我除了手动制作之外找不到其他方法。 有什么想法吗?
您可以在小位图上创建阴影图案,并将其与 BitmapShader 一起使用。
ApiDemos/graphics
中有一个名为 Pattern.java
的示例,它向您展示了如何操作。不过,如果您只需要绘制一个阴影矩形,那么手动进行阴影可能会更容易。
要按照@svdree的建议创建着色器,我们需要一个可重复的阴影部分,如下所示:
对于任何旋转 45° 的给定线,其水平或垂直交叉点为
hypot = √(thickness² + thickness²)
。任何边缘恰好包含两条线,因此我们需要一个 2×hypot
大小的方形位图。
根据图片,较白的线条来自
0, hypot/2
到hypot/2, 0
以及从hypot/2, size
到size, hypot/2
。要使线条到达边界末端,可以使用 SQUARE Cap。
将所有这些放在一起,这是代码:
fun Hatching45Shader(@Px lineWidth: Int, @ColorInt background: Int, @ColorInt lineColor: Int): Shader {
val hypot = hypot(lineWidth.toDouble(), lineWidth.toDouble()).toInt()
val bm = Bitmap.createBitmap(hypot + hypot, hypot + hypot, Bitmap.Config.ARGB_8888)
bm.eraseColor(background)
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
strokeWidth = lineWidth.toFloat()
color = lineColor
strokeCap = Paint.Cap.SQUARE
}
Canvas(bm).apply {
val half = hypot / 2f
drawLine(0f, half, half, 0f, paint)
val size = (hypot + hypot).toFloat()
drawLine(half, size, size, half, paint)
}
return BitmapShader(bm, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)
}
P。 S. 如果
lineColor
是半透明的,它将与 background
混合。这是故意的。