如何设置渐变样式来绘制对象?

时间:2011-12-22 07:48:20

标签: android

使用 Style:Fill 绘制箭头的代码如下:

paint.setColor(Color.parseColor("#bdc0dc"));
paint.setStyle(Style.FILL);
canvas.drawPath(arrowPath, paint);
paint.setColor(Color.BLACK);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
canvas.drawPath(arrowPath, paint);

我获得的输出是:

enter image description here

现在我要做的是将样式设置为Gradient(在android中不存在Style.gradient ...)以获得类似于下面给出的图像的箭头:

enter image description here

我该怎么做?我尝试在style.xml中添加样式但是无法在那里添加渐变,因为它接受item作为参数..

2 个答案:

答案 0 :(得分:99)

使用以下代码..

paint.setShader(new LinearGradient(0, 0, 0, getHeight(), Color.BLACK, Color.WHITE, Shader.TileMode.MIRROR));
    canvas.drawPath(arrowPath, paint);

答案 1 :(得分:1)

如果您想要多种颜色:

// Gradient Shade colors distribution setting uniform for now
private val positions = null //floatArrayOf(0f, 0.3f, 0.6f)

// Gradient Shade colors
private val colors = intArrayOf(
        ContextCompat.getColor(context,
                R.color.divider_gradient_start_color),
        ContextCompat.getColor(context,
                R.color.divider_gradient_center_color),
        ContextCompat.getColor(context,
                R.color.divider_gradient_end_color))

在OnDraw()

// Add Shader
gradientPaint.shader = LinearGradient(0f, 0f, measuredWidth.toFloat(),0f, 
                colors, 
                positions,
                Shader.TileMode.CLAMP)

canvas.drawPath(path, gradientPaint)