How to draw on canvas and convert to bitmap?

。_饼干妹妹 提交于 2020-01-01 17:00:49

问题


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!


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/32177375/how-to-draw-on-canvas-and-convert-to-bitmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!