How to draw on canvas in another thread?

I am developing an application and I need drawingg to run in a different thread. Now my code is:

public class PainterView extends View implements DrawingListener { //private GestureDetector detector; private Context context; private Painter painter; private Bitmap background; private Bitmap bitmap; private Paint bitmapPaint; private Path path; private Paint paint; private float x; private float y; private boolean isErasing=false; private boolean isTextDrawing=false; private ExecutorService pool; public PainterView(Context context, Painter painter) { super(context); this.context = context; this.painter = painter; pool=Executors.newFixedThreadPool(3); //detector = new GestureDetector(context, new GestureListener()); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } @Override protected void onDraw(final Canvas canvas) { if (bitmap != null) { pool.submit(new Runnable() { @Override public void run() { // TODO Auto-generated method stub synchronized (PainterView.this) { canvas.drawBitmap(background, 0, 0, bitmapPaint); canvas.drawBitmap(bitmap, 0, 0, bitmapPaint); canvas.drawPath(path, paint); } } }); } } @Override public boolean onTouchEvent(MotionEvent event) { //detector.onTouchEvent(event); x = event.getX(); y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: painter.touchStart(x, y); break; case MotionEvent.ACTION_MOVE: painter.touchMove(x, y); break; case MotionEvent.ACTION_UP: painter.touchUp(); break; } return true; } @Override public void onPictureUpdate(Bitmap background, Bitmap bitmap, Paint bitmapPaint, Path path, Paint paint) { this.background=background; this.bitmap = bitmap; this.bitmapPaint = bitmapPaint; this.path = path; this.paint = paint; invalidate(); } public void setPainter(Painter painter) { this.painter = painter; } } 

I thought that if I use ExecutorService, then the application can draw in a different thread, but this will not work - when I draw the device’s blinking screen. So, tell me, how can I use multithreading for painting using SurfaceHolder and other elements? I need to make as few changes in my code as possible.

+2
source share
1 answer

You can draw only the main user interface thread. You should use SurfaceView as it was specially created to support drawing from secondary streams.

One of the goals of this class is to provide a surface on which the secondary thread can be displayed on the screen. If you intend to use it like this, you need to know some semantics of the threads.

a source

Watch also video: Explore Android 1.28 Guide- Introduction to SurfaceView

0
source

Source: https://habr.com/ru/post/888188/


All Articles