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>
若有錯誤,歡迎指正留言!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/211956.html
標籤:其他
下一篇:區塊鏈畢設必讀論文【31】
