最新消息:欢迎访问Android开发中文站!商务联系微信:loading_in

Android 利用 Canvas 画画板

开发进阶 AndroidChina 6051浏览 0评论

首先新建一个项目工程,建立文件,如下图所示

首先配置页面布局文件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&lt;?&gt; 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&lt;?&gt; 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&gt;
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

然后用虚拟机测试如下所示:

可以在模拟器看一下,生成的文件

表示验证成功了

转载请注明:Android开发中文站 » Android 利用 Canvas 画画板

您必须 登录 才能发表评论!