matt matt
matt matt

Reputation: 215

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!

Upvotes: 4

Views: 7979

Answers (2)

XYL
XYL

Reputation: 108

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);
    }
});

Upvotes: 3

Jiang YD
Jiang YD

Reputation: 3311

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

Upvotes: 1

Related Questions