Android 简单画图板界面(附有代码)
进行Android画图板实现,我们对比一下在Java界面中画图板所需要的内容
1.JFrame ———— ImageView
组件,显示画图的内容
2.BufferedImage ———— Bitmap
缓存,画图的位置
3.Graphics ————
画图形 Canvas
设置绘图样式 Paint(在安卓中,画图与前者略有不同,分为了两个部分)
4.MouseListener ———— OnTouchListener
监听器(鼠标监听————触摸监听)
接下来我们开始实现:
第一步:获取ImageView
ImageView showView =(ImageView)this.findViewById(R.id.showView);
第二步:在ImageView中添加监听器
第三步:触摸画图
第四步:将Bitmap显示在ImageView上
代码如下:
MainActivity
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取ImageView
ImageView showView =(ImageView)this.findViewById(R.id.showView);
//获取监听器
DrawListener dl = new DrawListener(this);
//添加监听器
showView.setOnTouchListener(dl);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
监听器 DrawListener
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.Toast;
public class DrawListener implements OnTouchListener {
// Bitmap
Bitmap bitmap;
// Canvas
Canvas canvas;
// Paint
Paint p = new Paint();
// 获取坐标
float x1, x2, y1, y2;
public boolean onTouch(View v, MotionEvent event) {
// 根据事件源获取界面宽高,创建Bitmap
bitmap = Bitmap.createBitmap(v.getWidth(),v.getHeight(),Config.ARGB_8888);
canvas = new Canvas(bitmap);
p.setColor(Color.BLACK);
// 获取事件信息
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
x1 = event.getX();
y1 = event.getY();
} else if (action == MotionEvent.ACTION_UP) {
x2 = event.getX();
y2 = event.getY();
canvas.drawLine(x1, y1, x2, y2, p);
// 显示
ImageView showView = (ImageView) v;
showView.setImageBitmap(bitmap);
}
return true;
}
}
在xml文件中,我们仍需注意注意两点
1.ImageView宽度,高度应用match_parent
2.给ImageView一个id,并与MainActivity中一致
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/showView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world" />
</RelativeLayout>
若有错误,欢迎指正留言!!!