android項目 之 記事本(6)----- 加入手寫

???????想必大家都用過QQ的白板功能,里面主要有兩項,一個是涂鴉功能,事實上類似于上節的畫板功能,而還有一個就是手寫,那記事本怎么能沒有這個功能呢,今天就來為我們的記事本加入手寫功能。

?????? 先上圖,看看效果:

?????? 看了效果圖,是不是心動了呢?那就趕緊著手做吧,事實上,手寫功能并不難實現,大體就是全屏書寫,定時發送handle消息,更新activity。

?????? 實現手寫功能的主要步驟:

?????????????1. 自己定義兩個View,一個是TouchView,用于在上面繪圖,還有一個是EditText,用于將手寫的字顯示在當中,而且,要將兩個自己定義View通過FrameLayout幀式布局重疊在起,以實現全屏手寫的功能。

?????????????2? 在TouchView中實現寫字,并截取畫布中的字以Bitmap保存。

???????????? 3.?設置定時器,利用handle更新界面。

???????

????????以下是實現的細節:

??????????? 1. 手寫的界面設計:

????????????????????? 如上圖所看到的,和上節的畫板界面一致,底部分選項菜單條,有5個選項,各自是調整畫筆大小,畫筆顏色,撤銷,恢復,以及清空,對于這些功能,之后幾節再實現。

????????????????????布局文件activity_handwrite.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@android:color/white"><FrameLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:id="@+id/finger_layout"  ><com.example.notes.LineEditTextandroid:id="@+id/et_handwrite"android:layout_width="match_parent"android:layout_height="match_parent"android:scrollbars="vertical"android:fadingEdge="vertical"android:inputType="textMultiLine"android:gravity="top"android:textSize="20sp"android:layout_margin="5dp"android:focusable="true"android:lineSpacingExtra="10dp"android:textColor="#00000000"android:background="#00000000"/><com.example.notes.TouchViewandroid:id="@+id/touch_view"android:layout_width="fill_parent"android:layout_height="wrap_content"android:background="@android:color/transparent" ></com.example.notes.TouchView></FrameLayout><ImageView android:layout_width="match_parent"android:layout_height="wrap_content"android:src="@drawable/line"android:layout_above="@+id/paintBottomMenu"/><GridView android:id="@+id/paintBottomMenu" android:layout_width="match_parent"android:layout_height="45dp"android:numColumns="auto_fit"android:background="@drawable/navigationbar_bg"android:horizontalSpacing="10dp"android:layout_alignParentBottom="true"></GridView></RelativeLayout>

???????????????? 能夠看出,里面有兩個自己定義view,而且通過FrameLayout重疊在一起。???????

???????????

????????????????先來看com.example.notes.LineEditText,這個事實上和加入記事中的界面一樣,就是自己定義EditText,而且在字的以下畫一條線。

???????? LineEditText.java

public class LineEditText extends EditText {private Rect mRect;private Paint mPaint;public LineEditText(Context context, AttributeSet attrs) {// TODO Auto-generated constructor stubsuper(context,attrs);mRect = new Rect();mPaint = new Paint();mPaint.setColor(Color.GRAY);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);//得到EditText的總行數int lineCount = getLineCount();Rect r = mRect;Paint p = mPaint;//為每一行設置格式 for(int i = 0; i < lineCount;i++){//取得每一行的基準Y坐標,并將每一行的界限值寫到r中int baseline = getLineBounds(i, r);//設置每一行的文字帶下劃線canvas.drawLine(r.left, baseline+20, r.right, baseline+20, p);}}
}

???????? 還有一個就是com.example.notes.TouchView,實現了繪制,及定時更新界面的功能,詳細看代碼

?????????TouchView.java

public class TouchView extends View {private Bitmap  mBitmap,myBitmap;private Canvas  mCanvas;private Path    mPath;private Paint   mBitmapPaint;private Paint mPaint;private Handler bitmapHandler;GetCutBitmapLocation getCutBitmapLocation;private Timer timer;DisplayMetrics dm;private int w,h;public TouchView(Context context) {super(context);dm = new DisplayMetrics();((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);w = dm.widthPixels;h = dm.heightPixels;initPaint();}public TouchView(Context context, AttributeSet attrs) {super(context,attrs);dm = new DisplayMetrics();((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);w = dm.widthPixels;h = dm.heightPixels;initPaint();}//設置handlerpublic void setHandler(Handler mBitmapHandler){bitmapHandler = mBitmapHandler;}//初始化畫筆,畫布private void initPaint(){mPaint = new Paint();mPaint.setAntiAlias(true);mPaint.setDither(true);mPaint.setColor(0xFF00FF00);mPaint.setStyle(Paint.Style.STROKE);mPaint.setStrokeJoin(Paint.Join.ROUND);mPaint.setStrokeCap(Paint.Cap.ROUND);mPaint.setStrokeWidth(15);  getCutBitmapLocation = new GetCutBitmapLocation();//畫布大小 mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);mCanvas = new Canvas(mBitmap);  //全部mCanvas畫的東西都被保存在了mBitmap中mCanvas.drawColor(Color.TRANSPARENT);mPath = new Path();mBitmapPaint = new Paint(Paint.DITHER_FLAG);timer = new Timer(true);}/*** 處理屏幕顯示*/Handler handler = new Handler(){public void handleMessage(Message msg) {switch (msg.what) {			case 1:	myBitmap = getCutBitmap(mBitmap); Message message = new Message();message.what=1;Bundle bundle = new Bundle();;bundle.putParcelable("bitmap",myBitmap);message.setData(bundle);bitmapHandler.sendMessage(message);RefershBitmap();break;}super.handleMessage(msg);}};/*** 發送消息給handler更新ACTIVITY		*/TimerTask task = new TimerTask() {public void run() {Message message = new Message();message.what=1;Log.i("線程", "來了");handler.sendMessage(message);}};//分割畫布中的字并返回public Bitmap getCutBitmap(Bitmap mBitmap){//得到手寫字的四周位置,并向外延伸10pxfloat cutLeft = getCutBitmapLocation.getCutLeft() - 10;float cutTop = getCutBitmapLocation.getCutTop() - 10;float cutRight = getCutBitmapLocation.getCutRight() + 10;float cutBottom = getCutBitmapLocation.getCutBottom() + 10;cutLeft = (0 > cutLeft ? 0 : cutLeft);cutTop = (0 > cutTop ? 0 : cutTop);cutRight = (mBitmap.getWidth() < cutRight ? mBitmap.getWidth() : cutRight);cutBottom = (mBitmap.getHeight() < cutBottom ? mBitmap.getHeight() : cutBottom);//取得手寫的的高度和寬度 float cutWidth = cutRight - cutLeft;float cutHeight = cutBottom - cutTop;Bitmap cutBitmap = Bitmap.createBitmap(mBitmap, (int)cutLeft, (int)cutTop, (int)cutWidth, (int)cutHeight);if (myBitmap!=null ) {myBitmap.recycle();myBitmap= null;}return cutBitmap;}//刷新畫布private void RefershBitmap(){initPaint();invalidate();if(task != null)task.cancel();}@Overrideprotected void onDraw(Canvas canvas) {            canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);     //顯示舊的畫布       canvas.drawPath(mPath, mPaint);  //畫最后的path}private float mX, mY;private static final float TOUCH_TOLERANCE = 4;//手按下時private void touch_start(float x, float y) {mPath.reset();//清空pathmPath.moveTo(x, y);mX = x;mY = y;if(task != null)task.cancel();//取消之前的任務task = new TimerTask() {@Overridepublic void run() {Message message = new Message();message.what=1;Log.i("線程", "來了");handler.sendMessage(message);}};getCutBitmapLocation.setCutLeftAndRight(mX,mY);}//手移動時private void touch_move(float x, float y) {float dx = Math.abs(x - mX);float dy = Math.abs(y - mY);if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {mPath.quadTo(mX, mY, x, y);// mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);//源碼是這樣寫的,但是我沒有弄明確,為什么要這樣?mX = x;mY = y;if(task != null)task.cancel();//取消之前的任務task = new TimerTask() {@Overridepublic void run() {Message message = new Message();message.what=1;Log.i("線程", "來了");handler.sendMessage(message);}};getCutBitmapLocation.setCutLeftAndRight(mX,mY);}}//手抬起時private void touch_up() {//mPath.lineTo(mX, mY);mCanvas.drawPath(mPath, mPaint);mPath.reset();if (timer!=null) {if (task!=null) {task.cancel();task = new TimerTask() {public void run() {Message message = new Message();message.what = 1;handler.sendMessage(message);}};timer.schedule(task, 1000, 1000);				//2200秒后發送消息給handler更新Activity}}else {timer = new Timer(true);timer.schedule(task, 1000, 1000);					//2200秒后發送消息給handler更新Activity}}//處理界面事件@Overridepublic boolean onTouchEvent(MotionEvent event) {float x = event.getX();float y = event.getY();switch (event.getAction()) {case MotionEvent.ACTION_DOWN:touch_start(x, y);invalidate(); //刷新break;case MotionEvent.ACTION_MOVE:touch_move(x, y);invalidate();break;case MotionEvent.ACTION_UP:touch_up();invalidate();break;}return true;}}

??????? 這里面的難點就是利用TimerTask和Handle來更新界面顯示,須要在onTouchEvent的三個事件中都要通過handle發送消息來更新顯示界面。

????????

?????? 接下來就是在activity里通過handle來得到繪制的字,并加入在editText中。

???????關于配置底部菜單,以及頂部標題欄,這里不再贅述,直接怎樣將繪制的字得到,并加入在edittext中:

??????

??????? ?得到繪制字體的Bitmap

	   //處理界面Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);Bundle bundle = new Bundle();bundle = msg.getData();Bitmap myBitmap = bundle.getParcelable("bitmap");	InsertToEditText(myBitmap);}};


????????? 當中myBitmap就是取得的手寫字,保存在Bitmap中,??InsertToEditText(myBitmap);是將該圖片加入在edittext中,詳細例如以下:

	private LineEditText et_handwrite;????? 
	et_handwrite = (LineEditText)findViewById(R.id.et_handwrite);

???????????????????

	   //將手寫字插入到EditText中private void InsertToEditText(Bitmap mBitmap){int imgWidth = mBitmap.getWidth();int imgHeight = mBitmap.getHeight();//縮放比例float scaleW = (float) (80f/imgWidth);float scaleH = (float) (100f/imgHeight);Matrix mx = new Matrix();//對原圖片進行縮放mx.postScale(scaleW, scaleH);mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, imgWidth, imgHeight, mx, true);//將手寫的字插入到edittext中SpannableString ss = new SpannableString("1");ImageSpan span = new ImageSpan(mBitmap, ImageSpan.ALIGN_BOTTOM);ss.setSpan(span, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);et_handwrite.append(ss);}

??????????? 這樣,就實現了手寫的功能,下節就實現手寫字的撤銷,恢復,以及清空的功能。

????????? ???????

????????????

??????????????

?

?

?

??????

轉載于:https://www.cnblogs.com/blfshiye/p/4264408.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273413.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273413.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273413.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

HTTP協議中常見請求方法以及一些常見錯誤代碼

GET&#xff1a; 請求指定的頁面信息&#xff0c;并返回實體主體。 HEAD&#xff1a; 只請求頁面的首部。 POST&#xff1a; 請求服務器接受所指定的文檔作為對所標識的URI的新的從屬實體。 PUT&#xff1a; 從客戶端向服務器傳送的數據取代指定的文檔的內容。 DELETE&#xff…

license文件生成原理

byte解密weblogic加密oraclehex現在很多J2EE應用都采用一個license文件來授權系統的使用&#xff0c;特別是在系統購買的早期&#xff0c;會提供有限制的license文件對系統進行限制&#xff0c;比如試用版有譬如IP、日期、最大用戶數量的限制等。 而license控制的方法又有很…

linux常用關機命令及其區別-Shutdown halt reboot init

1.shutdown shutdown命令安全地將系統關機。 shutdown 參數說明: [-t] 在改變到其它runlevel之前﹐告訴init多久以后關機。 [-r] 重啟計算器。 [-k] 并不真正關機﹐只是送警告信號給每位登錄者〔login〕。 [-h] 關機后關閉電源〔halt〕。 [-n] 不用init﹐而是自己來關機。不鼓…

CSS3動畫@keyframes中translate和scale混用出錯問題

在寫基于網頁的2048時&#xff0c;想讓一個元素出現時已經通過translate屬性固定在指定位置&#xff0c;同時顯示動畫scale(0)-->scale(1)&#xff0c;以實現放大出現效果。 CSS代碼為 -webkit-keyframes mymove_failed{0% {-webkit-transform:translate(50px,50px) scale…

metero學習

博客園首頁新隨筆聯系訂閱管理最新隨筆 最新評論 node.js相關的中文文檔及教程 (轉) Posted on 2013-08-30 10:40 小小清清 閱讀(61) 評論(0) 編輯 收藏 node.js api中英文對照: http://docs.cnodejs.net/cman/ node.js入門中文版: http://nodebeginner.org/index-zh-cn.html e…

Linux統計單個文件統計

語法&#xff1a;wc [選項] 文件… 說明&#xff1a;該命令統計給定文件中的字節數、字數、行數。如果沒有給出文件名&#xff0c;則從標準輸入讀取。wc同時也給出所有指定文件的總統計數。字是由空格字符區分開的最大字符串。 該命令各選項含義如下&#xff1a; - c 統計字節數…

jQuery慢慢啃之事件對象(十一)

1.event.currentTarget//在事件冒泡階段中的當前DOM元素 $("p").click(function(event) {alert( event.currentTarget this ); // true }); 2.event.data//當前執行的處理器被綁定的時候&#xff0c;包含可選的數據傳遞給jQuery.fn.bind。 $("a").ea…

Linuxcurl命令參數詳解

Linuxcurl是通過url語法在命令行下上傳或下載文件的工具軟件&#xff0c;它支持http,https,ftp,ftps,telnet等多種協議&#xff0c;常被用來抓取網頁和監控Web服務器狀態。1.linuxcurl抓取網頁&#xff1a;抓取百度&#xff1a;curlhttp://www.baidu.com如發現亂碼&#xff0c;…

android解析XML總結(SAX、Pull、Dom三種方式)

在android開發中&#xff0c;經常用到去解析xml文件&#xff0c;常見的解析xml的方式有一下三種&#xff1a;SAX、Pull、Dom解析方式。 今天解析的xml示例&#xff08;channels.xml&#xff09;如下&#xff1a; 1 <?xml version"1.0" encoding"utf-8"…

查看Eclipse中的jar包的源代碼:jd-gui.exe

前面搞了很久的使用JAD&#xff0c;各種下載插件&#xff0c;最后配置好了&#xff0c;還是不能用&#xff0c;不知道怎么回事&#xff0c; 想起一起用過的jd-gui.exe這個工具&#xff0c;是各種強大啊&#xff01;&#xff01;&#xff01; 只需要把jar包直接扔進去就可以了&a…

maven scope含義的說明

compile &#xff08;編譯范圍&#xff09; compile是默認的范圍&#xff1b;如果沒有提供一個范圍&#xff0c;那該依賴的范圍就是編譯范圍。編譯范圍依賴在所有的classpath 中可用&#xff0c;同時它們也會被打包。 provided &#xff08;已提供范圍&#xff09; provided 依…

此地址使用了一個通常用于網絡瀏覽以外的端口。出于安全原因,Firefox 取消了該請求...

FirFox打開80以外的端口&#xff0c;會彈出以下提示&#xff1a; “此地址使用了一個通常用于網絡瀏覽以外的端口。出于安全原因&#xff0c;Firefox 取消了該請求。”。 解決方法如下&#xff1a; 在Firefox地址欄輸入about:config,然后在右鍵新建一個字符串鍵network.securit…

Java操作shell腳本

public class Exec {private static ILogger logger LoggerFactory.getLogger(Exec.class);public Exec() {super();}/*** 執行命令&#xff08;如Shell腳本&#xff09;<br>* * param cmd 操作命令* param timeout 超時時間* return 命令執行過程輸出內容* * throws IO…

Mysql更新插入

在向表中插入數據的時候&#xff0c;經常遇到這樣的情況&#xff1a;1. 首先判斷數據是否存在&#xff1b; 2. 如果不存在&#xff0c;則插入&#xff1b;3.如果存在&#xff0c;則更新。 在 SQL Server 中可以這樣處理&#xff1a; if not exists (select 1 from t where id …

信息加密之信息摘要加密MD2、MD4、MD5

對于用戶數據的保密一直是各個互聯網企業頭疼的事&#xff0c;那如何防止用戶的個人信息泄露呢&#xff1f;今天為大家介紹一種最簡單的加密方式--信息摘要算法MD。它如何來保護用戶的個人信息呢&#xff1f;其實很簡單&#xff0c;當獲得到用戶的信息后&#xff0c;先對其進行…

Java 從網絡上下載文件

/*** 下載文件到本地 */public static void downloadPicture(String imageUrl, String filename){ URL url;try {url new URL(imageUrl);//打開網絡輸入流DataInputStream dis new DataInputStream(url.openStream());//建立一個新的文件FileOutputStream fos new FileOutp…

An error was encountered while running(Domain=LaunchSerivcesError, Code=0)

今天突然遇到這樣一個錯誤&#xff0c;編譯可以通過&#xff0c;但是運行就會彈出這個錯誤提示&#xff1a; An error was encountered while running(DomainLaunchSerivcesError, Code0) 解決辦法就是重置模擬器。 點擊模擬器菜單中的Reset Contents and Settings&#xff0c;…

hdu 4091 線性規劃

分析轉自&#xff1a;http://blog.csdn.net/dongdongzhang_/article/details/7955136 題意 &#xff1a; 背包能裝體積為N, 有兩種寶石&#xff0c; 數量無限&#xff0c; 不能切割。 分別為 size1 value 1 size2 value2 問背包能裝最大的價值&#xff1f; 思路 &#xff…

linux fmt命令

簡單的格式化文本 fmt [option] [file-list] fmt通過將所有非空白行的長度設置為幾乎相同&#xff0c;來進行簡單的文本格式化 參數 fmt從file-list中讀取文件&#xff0c;并將其內容的格式化版本發送到標準輸出。如果不制定文件名或者用連字符&#xff08;-&#xff09;來替代…

基于 jQuery支持移動觸摸設備的Lightbox插件

Swipebox是一款支持桌面、移動觸摸手機和平板電腦的jquery Lightbox插件。該lightbox插件支持手機的觸摸手勢&#xff0c;支持桌面電腦的鍵盤導航&#xff0c;并且支持視頻的播放。 在線預覽 源碼下載 簡要教程 Swipebox是一款支持桌面、移動觸摸手機和平板電腦的jQuery Ligh…