Search code examples
javaandroid-canvas

My canvas.drawtext() doesn't work


I have an application, where I use Canvas for digital signature.

The canvas works well, but I also would like to have on the canvas already a text which would say - Signed on DD:MM:YYYY, HH:MM. I know how to use a calendar and put a date, but the order canvas.drawtext() doesn't work. Any ideas what I'm doing wrong?

PS - Everything else works well, I just want to add that text. :)

public class signature extends View {
        private static final float STROKE_WIDTH = 5f;
        private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
        private Paint paint = new Paint();
        private Path path = new Path();

        private float lastTouchX;
        private float lastTouchY;
        private final RectF dirtyRect = new RectF();

        public signature(Context context, AttributeSet attrs) {
            super(context, attrs);
            paint.setAntiAlias(true);
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeWidth(STROKE_WIDTH);
            paint.setTextSize(100);



        }

        public void save(View v, String StoredPath) {
            Log.v("tag", "Width: " + v.getWidth());
            Log.v("tag", "Height: " + v.getHeight());
            if (bitmap == null) {
                bitmap = Bitmap.createBitmap(mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);
            }

            Canvas canvas = new Canvas(bitmap);

            canvas.drawText("Example text", 100, 100, paint);

            try {

                // Output the file
                FileOutputStream mFileOutStream = new FileOutputStream(StoredPath);
                v.draw(canvas);
                // Convert the output file to Image such as .png
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
                mFileOutStream.flush();
                mFileOutStream.close();



            } catch (Exception e) {
                Log.v("log_tag", e.toString());
            }
        }

Solution

  • You are drawing your view on top of the text.

    change v.draw(canvas) to before canvas.drawText