标签:touch nal color widget convert gen ase find uri
package com.itheima.paintboard;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Bitmap.CompressFormat;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class MainActivity extends Activity {
private int startX;
private int startY;
private Paint paint;
private Canvas canvas;
private ImageView iv;
private Bitmap bmCopy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bitmap bmSrc = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
//白纸
bmCopy = Bitmap.createBitmap(bmSrc.getWidth(), bmSrc.getHeight(), bmSrc.getConfig());
//笔
paint = new Paint();
//画板
canvas = new Canvas(bmCopy);
//作画
canvas.drawBitmap(bmSrc, new Matrix(), paint);
iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bmCopy);
iv.setOnTouchListener(new OnTouchListener() {
//用户手指只要触摸屏幕,就会产生触摸事件
@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);
//刷新,因为每次滑动绘画时,图片保存在缓存里,所以需要重新设置ImageView进行刷新到界面上
iv.setImageBitmap(bmCopy);
//把本此画线的终点设置为下一次画线的起点
startX = newX;
startY = newY;
break;
//手指抬起
case MotionEvent.ACTION_UP:
break;
}
//true表示告诉系统,这个触摸事件由iv处理
//false表示不处理该触摸事件,事件往上传递
return true;
}
});
}
public void red(View v){
paint.setColor(Color.RED);
}
public void green(View v){
paint.setColor(Color.GREEN);
}
public void brush(View v){
//改变线条粗细
paint.setStrokeWidth(8);
}
public void save(View v){
File file = new File("sdcard/dazuo.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
//把图片压缩到本地文件
bmCopy.compress(CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//手动发一个sd卡就绪广播
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
sendBroadcast(intent);
}
}
标签:touch nal color widget convert gen ase find uri
原文地址:http://www.cnblogs.com/SoulCode/p/6393342.html