Android绘图-Gradient对象

定义

Gradient(梯度)在如许多图形编辑器,包括Photoshop指的是多个颜色之间的平滑过渡,而不是仅使用单个颜色来填充区域.

Android API提供3种不同的渐变:LinearGradient,RadialGradient和SweepGradient.

使用

这些都是Shader的子类.您可以在Paint对象上设置Shader,然后使用该Paint绘制任何形状.根据渐变的种类,它们之间的颜色和过渡将被填充.

Android绘图-Gradient对象_第1张图片
效果图
Bitmap test = Bitmap.createBitmap(640, 200, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(test);
{ // draw a dark gray background
    Paint backgroundPaint = new Paint();
    backgroundPaint.setARGB(255, 24, 24, 24);
    c.drawPaint(backgroundPaint);
}
Path heart = new Path();
{ // prepare a heart shape
    heart.moveTo(110, 175);
    heart.lineTo(10, 75);
    RectF leftCircle = new RectF(10, 25, 110, 125);
    heart.arcTo(leftCircle, 180, 180);
    RectF rightCircle = new RectF(110, 25, 210, 125);
    heart.arcTo(rightCircle, 180, 180);
    heart.close();
}
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(18f);
int[] colors = {
        0xFFFFFF88, // yellow
        0xFF0088FF, // blue
        0xFF000000, // black
        0xFFFFFF88  // yellow
};
float[] positions = {0.0f, 0.33f, 0.66f, 1.0f};
{ // draw the left heart
    SweepGradient sweepGradient;
    { // initialize the sweep gradient
        sweepGradient = new SweepGradient(50, 50, colors, positions);
        paint.setShader(sweepGradient);
    }
    c.drawPath(heart, paint);
    c.drawText("SweepGradient", 50, 190, paint);
}
{ // draw the middle heart
    LinearGradient linearGradient;
    { // initialize a linear gradient
        linearGradient = new LinearGradient(250, 0, 350, 150, colors, positions, Shader.TileMode.CLAMP);
        paint.setShader(linearGradient);
    }
    heart.offset(210, 0); // move the heart shape to the middle
    c.drawPath(heart, paint);
    c.drawText("LinearGradient", 260, 190, paint);
}
{ // draw the right heart
    RadialGradient radialGradient;
    { // initialize a linear gradient
        radialGradient = new RadialGradient(550, 50, 100, colors, positions, Shader.TileMode.CLAMP);
        paint.setShader(radialGradient);
    }
    heart.offset(210, 0); // move the heart shape to the right
    c.drawPath(heart, paint);
    c.drawText("RadialGradient", 470, 190, paint);
}
{ // save the bitmap
    String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "test.png";
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(filename);
        test.compress(Bitmap.CompressFormat.PNG, 90, out);
    } catch (Exception e) {
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }
}

引用

stackoverflow

你可能感兴趣的:(Android绘图-Gradient对象)