android 图片画画板
canvas.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="保存" android:onClick="save" /> <ImageView android:id="@+id/image" android:layout_width="480px" android:layout_height="320px" /> </LinearLayout>
package com.example.imageLoadBigImg; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * 图片画板 * Created by Heyiyong on 2014-4-11 下午1:58. */ public class ImageCanvasActivity extends Activity { private ImageView imageView; private Bitmap bitmap; private Canvas canvas; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.canvas); imageView = (ImageView) findViewById(R.id.image); //创建画笔样式 final Paint paint = new Paint(); paint.setColor(Color.RED); //创建一个可修改的bitmap bitmap = Bitmap.createBitmap(480, 320, Bitmap.Config.ARGB_4444); //以bitmap为模板,创建画板对象 canvas = new Canvas(bitmap); canvas.drawColor(Color.WHITE); imageView.setOnTouchListener(new View.OnTouchListener() { int startX; int startY; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN://按下的时候 startX = (int) event.getX(); startY = (int) event.getY(); break; case MotionEvent.ACTION_MOVE://移动的时候 int newX = (int) event.getX(); int newY = (int) event.getY(); canvas.drawLine(startX, startY, newX, newY, paint); //重置初始位置 startX = newX; startY = newY; //将画板的图片设置上去 imageView.setImageBitmap(bitmap); break; case MotionEvent.ACTION_UP://手放开的时候 break; } return true; } }); } public void save(View view) { try { File file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg"); FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);//第一个参数为图片格式 fos.close(); Toast.makeText(this, "保存图片成功", 2000).show(); //模拟消息:SD卡被重新挂载了 Intent intent = new Intent(); intent.setAction(intent.ACTION_MEDIA_MOUNTED); intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory())); sendBroadcast(intent); } catch (FileNotFoundException e) { Toast.makeText(this, "保存图片失败", 2000).show(); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
本文出自 无忧之路 - 博客园