编程语言
首页 > 编程语言> > [Java] [Android] 画板

[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还是正常的

标签:Canvas,Java,BasicCanvas,int,画板,import,Android,public,android
来源: https://blog.csdn.net/qq_53530146/article/details/122763010