Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw on canvas and convert to bitmap?

I'm tring to draw some line and shapes on canvas and then convert it to bitmap on ImageView. I'm usin a custom class that extands "View" and on "OnDraw method i'm drawing the lines. here is my code(this class only draw simple lines) :

public class finalDraw extends View {
        public finalDraw(Context context) {
            super(context);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            Paint paint = new Paint();
            paint.setColor(Color.BLUE);
            for (int i = 0; i <100; i++) {
                 canvas.drawLine(xStart * i + 50 , yStart , stopX + 30 , stopY,paint); 
            }

            invalidate();
        }
    }

How can i get the drawing result and show it on ImageView? Thanks!

like image 540
matt matt Avatar asked Oct 16 '25 18:10

matt matt


2 Answers

Found this article may help: http://www.informit.com/articles/article.aspx?p=2143148&seqNum=2

draw.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        Bitmap imageBitmap = Bitmap.createBitmap(imageView.getWidth(), imageView.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(imageBitmap);
        float scale = getResources().getDisplayMetrics().density;
        Paint p = new Paint();
        p.setColor(Color.BLUE);
        p.setTextSize(24*scale);
        canvas.drawText("Hello", imageView.getWidth()/2, imageView.getHeight()/2, p);
        imageView.setImageBitmap(imageBitmap);
    }
});
like image 111
XYL Avatar answered Oct 19 '25 08:10

XYL


Create a Canvas with a bitmap, by Canvas(Bitmap bitmap). All draws to that canvas will in that bitmap.

like image 36
Jiang YD Avatar answered Oct 19 '25 09:10

Jiang YD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!