Android将Text添加到Canvas失败

时间:2013-12-13 07:23:49

标签: android android-canvas

我打算通过绘画创建一个jpeg。元素是文本和图像。在实现时,只绘制图像和背景颜色,但没有文本。即使我已经调用了canvas.drawText

,我也没有发生什么事

以下是我的代码

String folderName = "droidCanvas";
                String textString ="Hello , I am user 12345. \n Below is my signature.";
                String fileNameString = "test.jpg";
                File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()  + File.separator   + folderName );
                if(!folder.exists()){
                    folder.mkdir();
                }

            File bmpFile = new File(folder.getAbsolutePath()  + File.separator   + fileNameString );
            if(!bmpFile.exists()){
                try {
                    bmpFile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            //Draw something
            Paint paint = new Paint();
            paint.setColor(Color.RED); 

            Paint txtPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

            txtPaint.setColor(Color.BLACK);  
            txtPaint.setTextSize(20);
            bmpBase = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            canvas = new Canvas(bmpBase);
            canvas.drawColor(Color.WHITE);
            canvas.drawCircle(w/2, h/2, 300, paint);
            canvas.drawText(textString ,w/2, 0 , txtPaint);

            //Export to jpeg
            try
            {
                fos = new FileOutputStream(bmpFile);
                bmpBase.compress(Bitmap.CompressFormat.JPEG, 100, fos);

                fos.flush();
                fos.close();
                fos = null;
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {
                if (fos != null)
                {
                    try
                    {
                        fos.close();
                        fos = null;
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            }

1 个答案:

答案 0 :(得分:2)

尝试canvas.drawText(textString ,w/2, h/2 , txtPaint);,您至少可以看到该文字。然后你可以稍后重新定位它。现在它正在被绘制,但你无法看到它,因为它处于极端顶部中心和界限之外。

如果您想将其放在左上角,请执行以下操作:

canvas.drawText(textString ,0 , txtPaint.getFontSpacing(), txtPaint);