在图像上写文本时出错

时间:2014-03-20 11:43:58

标签: java android canvas

我尝试在我的图片上写一个文字:

private Bitmap drawText() {
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
             R.drawable.test); 

    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setTextSize(5);
    canvas.drawText("Some Text here", 5, 5, paint);

    Bitmap resBitmap = Bitmap.createBitmap(canvas.getWidth(),
            canvas.getHeight(), Config.RGB_565);
    canvas.setBitmap(resBitmap);
    return resBitmap;

}

结果是完全黑色的图像。我做错了什么?

3 个答案:

答案 0 :(得分:3)

免责声明:我不是Android开发人员。我从来没有写过像这样的代码。这只是我对文档的解释......

我怀疑你实际想要将位图设置为更早绘制,然后将另一个位图绘制到画布中。如下所示:

private Bitmap drawText() {
    // Load the existing image to get some dimensions
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
        R.drawable.test); 

    // Create a result bitmap and a canvas which draws onto it
    Bitmap resBitmap = Bitmap.createBitmap(bitmap.getWidth(),
        bitmap.getHeight(), Config.RGB_565);
    Canvas canvas = new Canvas(resBitmap);

    // Draw the existing image into the canvas
    canvas.drawBitmap(bitmap, 0f, 0f, null);

    // Draw text on top
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setTextSize(5);
    canvas.drawText("Some Text here", 5, 5, paint);

    return resBitmap;
}

答案 1 :(得分:0)

你从这个

设置画布的背景
  paint.setColor(Color.BLACK);

default text color is also black,你只能看到那个黑屏

试试这个

    paint.setColor(Color.GREEN);

答案 2 :(得分:0)

更改画布的背景颜色和前景色。

Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);

paint.setColor(android.R.color.black);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);

确保文本的颜色必须与背景颜色不同