[Java] [Android] 画板

2022/2/1 11:28:30

本文主要是介绍[Java] [Android] 画板,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

代码

BasicCanvas.java

package com.Diamond.canvas;

import android.view.SurfaceView;
import android.view.SurfaceHolder;
import android.graphics.Bitmap;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Color;

public class BasicCanvas extends SurfaceView implements SurfaceHolder.Callback {
    public class DrawThread extends Thread {
        @Override
        public void run() {
            while(true) {
                int bw = bitmap.getWidth();
                int bh = bitmap.getHeight();
                
                Canvas canvas = getCanvas();
                canvas.drawARGB(255,0,0,0);
                canvas.drawBitmap(bitmap,new Rect(0,0,bw,bh),new Rect(0,0,bw,bh),null);
                update(canvas);
            }
        }
    }
    
    public Bitmap bitmap;
    public DrawThread thread;
    public SurfaceHolder holder;
    public BasicCanvas(Context context) {
        super(context);
        holder = getHolder();
        holder.addCallback(this);
    }
    
    
    
    public Canvas getCanvas() {
        return holder.lockCanvas();
    }
    public BasicCanvas update(Canvas canvas) {
        holder.unlockCanvasAndPost(canvas);
        return this;
    }
    
    
    
    public BasicCanvas createNew(int width,int height) {
        bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        return this;
    }
    
    public BasicCanvas clear(int color) {
        getPaintableCanvas().drawColor(color);
        return this;
    }
    
    public Canvas getPaintableCanvas() {
        return new Canvas(bitmap);
    }
    
    
    
    @Override
    public void surfaceCreated(SurfaceHolder p1) {
        bitmap = Bitmap.createBitmap(getWidth(),getHeight(),Bitmap.Config.ARGB_8888);
        
        thread = new DrawThread();
        thread.start();
    }
    @Override
    public void surfaceChanged(SurfaceHolder p1, int p2, int p3, int p4) {
    }
    @Override
    public void surfaceDestroyed(SurfaceHolder p1) {
    }
}

用法

这是一个非常简单的类,把画图线程放了进去,只要调用getPaintableCanvas()就能获得一个Canvas对象,然后进行画图操作,最后什么都不用干,线程会自动把图画出来

提示

我继承BasicCanvas的时候出了问题,明明直接用BasicCanvas还是正常的



这篇关于[Java] [Android] 画板的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程