Android 利用 Canvas 畫畫板

陽陽的部落格發表於2015-07-14

首先新建一個專案工程,建立檔案,如下圖所示

首先配置頁面佈局檔案activity_main.xml,如下圖所示:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bg"
         />
    <TextView 
          android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="畫筆的粗細"
        />
    <SeekBar 
         android:id="@+id/sb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="256"
        />
    <TextView 
          android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="顏色"
        />
    <Spinner 
        android:id="@+id/sp"
         android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:entries="@array/color"
        />
    <Button 
            android:id="@+id/btn"
          android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="儲存"
        />

</LinearLayout>

然後書寫主頁的程式碼MainActivity.java程式碼如下

package com.xunfang.drawing;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.MonthDisplayHelper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {
    private SeekBar sb;
    private ImageView iv;
    private Button btn;
    private Spinner sp;
    private String[] color ;

    private Bitmap bm;
    private Bitmap copy;
    private  Canvas canvas;
    private Paint paint;
    private File file;
    private int yanse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       //拿到在xml檔案中定義的顏色陣列
        color = getResources().getStringArray(R.array.color) ;
        //例項化
        initData();
        //設定監聽器
        setLister();
        //畫畫
        loadingImage();

    }
    private void loadingImage() {
        // 載入原始圖片
        bm = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
        // 需要建立一個和原始的圖片大小一樣的空白圖片(一張紙,上面沒有任何資料)
        copy = bm.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
        // 需要一個畫板,畫板上鋪上白紙
        canvas= new Canvas(copy);
        // 建立畫筆
        paint= new Paint();

        // 給imageView空間載入一個滑動監聽器
        iv.setOnTouchListener(new OnTouchListener() {
            int startx;
            int starty;
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 拿到動作
                int type = event.getAction();
                switch (type) {
                case MotionEvent.ACTION_DOWN:
                    startx = (int) event.getX();
                    starty = (int) event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int endx = (int) event.getX();
                    int endy = (int) event.getY();
                    //畫畫
                    canvas.drawLine(startx, starty, endx, endy, paint);
                    startx = (int) event.getX();
                    starty = (int) event.getY();
                    iv.setImageBitmap(copy);
                    break;
                case MotionEvent.ACTION_UP:

                    break;
                }
                return true;
            }
        });

    }
    private void setLister() {
        //下拉框
        sp.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                Toast.makeText(getApplicationContext(), "你點選的是:" +  color[position], 0).show();                
                switch (position) {
                case 1:
                    paint.setColor(Color.GREEN);
                    break;
                case 2:
                    paint.setColor(Color.BLUE);
                    break;
                case 3:
                    paint.setColor(Color.BLACK);
                    break;
                case 4:
                    paint.setColor(Color.YELLOW);
                    break;
                case 0:
                    paint.setColor(Color.RED);
                    break;
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        //儲存
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    //指定圖片的儲存路徑
                    file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/draw.png");
                    FileOutputStream fos = new FileOutputStream(file);
                    copy.compress(CompressFormat.PNG, 100, fos);
                    Toast.makeText(getApplicationContext(), "儲存成功", 0).show() ;
                } catch (Exception e) {
                }
                //欺騙系統,告訴系統插入一個sd卡
                Intent intent = new Intent();
                intent.setAction(intent.ACTION_MEDIA_MOUNTED);
                intent.setData(Uri.fromFile(file));
                sendBroadcast(intent);
            }
        });
    }
    private void initData() {
            sb = (SeekBar) findViewById(R.id.sb);
            btn = (Button) findViewById(R.id.btn);
            sp = (Spinner) findViewById(R.id.sp);
            iv = (ImageView) findViewById(R.id.iv);
    }

}

AndroidManifest.xml配置檔案如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xunfang.drawing"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

然後用虛擬機器測試如下所示:

可以在模擬器看一下,生成的檔案

表示驗證成功了

相關文章