Android實現繪畫板功能

實現流程:

        一、預期效果
        二、設置橫豎屏切換
        三、確定佈局
        四、自定義滑動條
        五、繪畫區域
        六、MainActivity

實現步驟:

一、預期效果

二、設置橫豎屏切換

screenOrientation屬性        作用
user 用戶當前設置的方向。
unspecified 由系統選擇顯示方向,不同的設備可能會有所不同。(旋轉手機,界面會跟著旋轉)
landscape 限制界面為橫屏,旋轉屏幕也不會改變當前狀態。
portrait 限制界面為豎屏,旋轉屏幕也不會改變當前狀態。
behind 與前一個activity方向相同。
sensor 根據傳感器定位方向,旋轉手機90度,180,270,360,界面都會發生變化。
nosensor 不由傳感器確定方向。旋轉設備的時候,界面不會跟著旋轉。初始界面方向由系統提供。
sensorLandscape (橫屏的旋轉,不會出現豎屏的現象)根據傳感器定位方向,旋轉手機180度界面旋轉。一般橫屏遊戲會是這個屬性。
sensorPortrait (豎屏的旋轉,不會出現橫屏的現象)根據傳感器定位方向,旋轉手機180度界面會旋轉。

三、確定佈局

因為橫豎屏切換後控件的寬高都是不一樣的,也就是不固定的,不能用線性佈局,而是根據相對位置進行佈局。先用constraintLayout約束,再將小控件組合成一個線性佈局,然後對整個線性佈局進行相對佈局。

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/operation"
        >
        <!--滑動條-->
        <com.example.a16drawboard.Slider
            android:id="@+id/slider"
            android:layout_width="20dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"
            app:layout_constraintLeft_toLeftOf="parent"
            />
        <!--畫板-->
        <com.example.a16drawboard.DrawBoardView
            android:id="@+id/board"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            app:layout_constraintLeft_toRightOf="@id/slider"
            app:layout_constraintRight_toLeftOf="@id/color"/>
    <!--選顏色-->
        <LinearLayout
            android:id="@+id/color"
            android:layout_width="60dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginRight="20dp"
            app:layout_constraintRight_toRightOf="parent"
            android:gravity="center">

            <Button
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:background="@color/colorAccent"
                android:onClick="choiceColor"/>

            <Button
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:background="@color/colorPrimary"
                android:onClick="choiceColor"/>
            <Button
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:background="#f00"
                android:onClick="choiceColor"/>
            <Button
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:background="#000"
                android:onClick="choiceColor"/>

        </LinearLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>

    <LinearLayout
        android:id="@+id/operation"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="#f00"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        android:gravity="center">

        <Button
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:text="撤銷"
            android:onClick="goBack"/>

        <Button
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:text="清空"
            android:onClick="clear"/>

        <Button
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:text="橡皮擦"
            android:onClick="eraser"/>

        <Button
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:text="保存"
            android:onClick="save"/>

        <Button
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:text="上一步"
            android:onClick="lastStep"/>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

四、自定義滑動條

public class Slider extends View {
    private int lineSize = 6; // 線條的粗細
    private int lineColor = Color.BLACK;// 默認線條顏色
    private Paint linePaint;

    private Paint circlePaint; // 圓點畫筆
    private int thumbColor = Color.MAGENTA; // 圓點顏色
    private int cx; // 中心點x
    private int cy; // 中心點y
    private int radius; // 小圓點半徑

    private int thumbScale = 4; // 圓點縮放尺寸
    private float position; // 觸摸點的坐標
    private Paint progressPaint; // 進度條進度的畫筆
    private int progressColor = Color.MAGENTA; // 進度條顏色

    public static int PROGRESS = 0; // 進度條
    public static int SLIDER = 1; // 滑動條
    private int style = PROGRESS; // 用戶選擇的樣式,默認為進度條

    public int max = 100; // 設置最大值
    public float progress; // 進度值

    private OnSliderChangeListener onSliderChangeListener; // 滑動改變監聽者

    public Slider(Context context) {
        super(context);
    }

    public Slider(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init(){
        // 背景線
        linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        linePaint.setColor(lineColor);
        linePaint.setStrokeWidth(lineSize);

        // 圓點
        circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        circlePaint.setColor(thumbColor);
        circlePaint.setStyle(Paint.Style.FILL);

        // 進度條
        progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        progressPaint.setColor(progressColor);
        progressPaint.setStrokeWidth(lineSize);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        if (getWidth() > getHeight()){
            // 橫著
            canvas.drawLine(0, getHeight()/2, getWidth(), getHeight()/2, linePaint);
            if (position>0){
                canvas.drawLine(0, getHeight()/2, position, getHeight()/2, progressPaint);
            }
            radius = getHeight()/thumbScale;
            cy = getHeight()/2;
            // 確定cx的值
            if (position < radius) {
                cx = radius;
            }else if (position > getWidth()-radius){
                cx = getWidth()-radius;
            }else {
                cx = (int) position;
            }
        }else{
            // 豎著
            canvas.drawLine(getWidth()/2, 0, getWidth()/2, getHeight(), linePaint);
            if (position>0){
                canvas.drawLine(getWidth()/2, 0, getWidth()/2, position, progressPaint);
            }
            radius = getWidth()/thumbScale;
            cx = getWidth()/2;
            // 確定中心點cy的值
            if (position<radius){
                cy = radius;
            }else if (position > getHeight()-radius){
                cy = getHeight()-radius;
            }else {
                cy = (int) position;
            }
        }
        // 畫小圓點
        if (style == SLIDER){
            canvas.drawCircle(cx,cy,radius,circlePaint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                // 圓點放大
                thumbScale = 2;
                // 點下去就到那個位置
                if (getWidth()>getHeight()){
                    // 橫向時,y不變 x改變
                    position = event.getX();
                }else {
                    // 縱向時,x不變 y改變
                    position = event.getY();
                }
                callback();
                break;
            case MotionEvent.ACTION_MOVE:
                // 獲取當前觸摸點的值XY
                if (getWidth()>getHeight()){
                    // 橫向時,y不變 x改變
                    position = event.getX();
                    if (position<0){
                        progress = 0;
                    }else if (position>getWidth()){
                        position = getWidth();
                    }
                }else {
                    // 豎著時,x不變 y改變
                    position = event.getY();
                    if (position<0){
                        progress = 0;
                    }else if (position>getHeight()){
                        position = getHeight();
                    }
                }
                callback();
                break;
            case MotionEvent.ACTION_UP:
                thumbScale = 4;
                break;
        }
        if (style == SLIDER){
            invalidate();
        }
        return true;
    }
    private void callback(){
        if (onSliderChangeListener != null){
            if (getWidth()>getHeight()){
                progress = position/getWidth();
            }else {
                progress = position/getHeight();
            }
            onSliderChangeListener.progressChange(progress*max);
        }
    }

    public int getStyle() {
        return style;
    }

    public void setStyle(int style) {
        this.style = style;
    }

    public float getProgress() {
        return progress;
    }

    public void setProgress(int progress){
        // 計算比例
        float rate = (float)(progress*1.0/max);
        setProgress(rate);
    }
    public void setProgress(float progress) {
        this.progress = progress;

        if (progress <1.001) {
            // 將進度值轉化為控件中的尺寸位置
            if (getWidth() > getHeight()) {
                position = progress * getWidth();
            } else {
                position = progress * getHeight();
            }
            invalidate();
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (getWidth() > getHeight()) {
            position = progress * getWidth();
        } else {
            position = progress * getHeight();
        }
    }

    public void setMax(int max) {
        this.max = max;
    }
    public interface OnSliderChangeListener{
        void progressChange(float progress);
    }

    public void setOnSliderChangeListener(OnSliderChangeListener onSliderChangeListener) {
        this.onSliderChangeListener = onSliderChangeListener;
    }
}

五、繪畫區域

public class DrawBoardView extends View {
    private ArrayList<Graph> graphs; // 操作數組
    private ArrayList<Graph> orginalGraphs; // 原始數組

    private int lineColor = Color.BLACK;
    private int lineSize = 5;
    Path mPath;

    public DrawBoardView(Context context) {
        super(context);
    }

    public DrawBoardView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init(){
        // 初始化數組
        graphs = new ArrayList<>();
        orginalGraphs = new ArrayList<>();
        setBackgroundColor(Color.WHITE);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 遍歷數組
        Iterator<Graph> iterator = graphs.iterator();
        while (iterator.hasNext()){
            // 從集合中獲取一個圖形對象
            Graph line = iterator.next();
            // 繪制圖形
            canvas.drawPath(line.path,line.paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                // 創建這條線對應的paint和path
                Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
                mPaint.setColor(lineColor);
                mPaint.setStrokeWidth(lineSize);
                mPaint.setStyle(Paint.Style.STROKE);
                mPath = new Path();

                // 設置圖形的起點
                mPath.moveTo(event.getX(),event.getY());

                // 保存當前這個圖形的詳細信息
                Graph temp = new Graph(mPaint,mPath);
                graphs.add(temp);
                orginalGraphs.add(temp);
                break;
            case MotionEvent.ACTION_MOVE:
                // 連接從path終點到當前觸摸點的線
                mPath.lineTo(event.getX(),event.getY());
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        invalidate();
        return true;
    }
    // 用私有類來管理圖形的畫筆和路徑
    private class Graph{
        Paint paint;
        Path path;

        public Graph(Paint paint,Path path){
            this.paint=paint;
            this.path=path;
        }
    }

    // 刪除最後一個圖形  撤銷
    public void removeLast(){
        if (graphs.size() >0){
            graphs.remove(graphs.size()-1);
            invalidate();
        }
    }
    // 刪除所有 清空
    public void removeAll(){
        graphs.clear();
        invalidate();
    }
    // 還原上一步
    public void returnToLastStep(){
        // 判斷緩存中是否有
        if (graphs.size() < orginalGraphs.size()){
            // 獲取上一步的索引值
            int index = graphs.size()-1+1;
            // 從緩存中獲取index,添加到操作數組中
            graphs.add(orginalGraphs.get(index));
            invalidate();
        }
    }
    public int getLineSize() {
        return lineSize;
    }

    public void setLineSize(int lineSize) {
        this.lineSize = lineSize;
    }

    public int getLineColor() {
        return lineColor;
    }

    public void setLineColor(int lineColor) {
        this.lineColor = lineColor;
    }
}

六、MainActivity

public class MainActivity extends AppCompatActivity {
    private DrawBoardView boardView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 獲取畫板對象
        boardView = findViewById(R.id.board);
        // 獲取滑動條對象
        final Slider slider = findViewById(R.id.slider);
        slider.setStyle(Slider.SLIDER);
        slider.setMax(30);
        slider.setOnSliderChangeListener(new Slider.OnSliderChangeListener() {
            @Override
            public void progressChange(float progress) {
                boardView.setLineSize((int) progress);
            }
        });
        slider.setProgress(boardView.getLineSize());

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 設置橫屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
    // 選擇顏色 獲取按鈕上面的背景顏色
    public void choiceColor(View view) {
        // 獲取按鈕上面的背景顏色
        ColorDrawable drawable = (ColorDrawable) view.getBackground();

        // 獲取顏色
        boardView.setLineColor(drawable.getColor());
    }

    // 撤回
    public void goBack(View view) {
        boardView.removeLast();
    }
    // 清空
    public void clear(View view) {
        boardView.removeAll();
    }
    // 橡皮擦
    public void eraser(View view) {
        // 獲取畫板的drawable
        ColorDrawable drawable = (ColorDrawable) boardView.getBackground();
        // 設置線條顏色和背景色相同
        if (drawable != null){
            boardView.setLineColor(drawable.getColor());
        }else {
            boardView.setLineColor(Color.TRANSPARENT);
        }
    }
    // 保存
    public void save(View view) {
    }
    // 還原
    public void lastStep(View view) {
        boardView.returnToLastStep();
    }
}

到這裡就結束啦。

以上就是Android實現畫板功能的詳細內容,更多關於Android 畫板功能的資料請關註WalkonNet其它相關文章!

推薦閱讀: