編輯:關於 Android 程式設計
前兩節我們學過 Bitmap 以及一些基本繪圖 API 的屬性與常用方法,但心裡總覺得不踏實,還是得動手寫點東西才能加深印象。因此本節安排兩個小實例:一是簡單畫圖板,二是擦衣服的趣味小 Demo。開始吧。
畫圖板大家都不陌生,很多手機都內建塗鴉功能。先梳理一下實現邏輯:
Q1:畫板放在哪裡?答:放在自訂 View 裡,於
onDraw()中完成繪製,同時 View 還有onTouchEvent方法可以獲取手勢。Q2:需要準備什麼?答:一支畫筆(Paint)、一塊畫布(Canvas)、一條記錄軌跡的路徑(Path)。由於每次劃線都是從上一個觸摸到本次觸摸的點連線,若不處理就會丟失先前內容,因此引入「雙緩衝」技術:先畫到 Bitmap 上,等畫完再一次性繪製到 View。
Q3:具體流程?答:初始化畫筆並設置顏色等參數;在
onMeasure()建立與 View 同尺寸的 Bitmap 與 Canvas;在onTouchEvent取得 X、Y 坐標連線,最後呼叫invalidate()重繪,把 Bitmap 內容畫到 Canvas 上。
MyView.java:
/** * Created by Jay on 2015/10/15 0015. */ public class MyView extends View{ private Paint mPaint; //繪制線條的Path private Path mPath; //記錄用戶繪制的Path private Canvas mCanvas; //內存中創建的Canvas private Bitmap mBitmap; //緩存繪制的內容 private int mLastX; private int mLastY; public MyView(Context context) { super(context); init(); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init(){ mPath = new Path(); mPaint = new Paint(); //初始化畫筆 mPaint.setColor(Color.GREEN); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); //結合處為圓角 mPaint.setStrokeCap(Paint.Cap.ROUND); // 設置轉彎處為圓角 mPaint.setStrokeWidth(20); // 設置畫筆寬度 } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = getMeasuredWidth(); int height = getMeasuredHeight(); // 初始化bitmap,Canvas mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); } //重寫該方法,在這裡繪圖 @Override protected void onDraw(Canvas canvas) { drawPath(); canvas.drawBitmap(mBitmap, 0, 0, null); } //繪制線條 private void drawPath(){ mCanvas.drawPath(mPath, mPaint); } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); int x = (int) event.getX(); int y = (int) event.getY(); switch (action) { case MotionEvent.ACTION_DOWN: mLastX = x; mLastY = y; mPath.moveTo(mLastX, mLastY); break; case MotionEvent.ACTION_MOVE: int dx = Math.abs(x - mLastX); int dy = Math.abs(y - mLastY); if (dx > 3 || dy > 3) mPath.lineTo(x, y); mLastX = x; mLastY = y; break; } invalidate(); return true; } }
運行效果圖:

你可以依需求擴展,例如加上調整畫筆大小、切換顏色、保存作品等功能,發散思維動手試試。
核心思路是:用 FrameLayout 疊放前後兩個 ImageView,前面的顯示「未擦除」狀態,後面的顯示「擦除後」狀態;為前面的 ImageView 設置 OnTouchListener,把手指觸碰點附近 20×20 個像素設為透明即可。
運行效果圖:

代碼實現:
Step 1:編寫選擇頁的界面,包含一個 ImageView、一個 Button 與一個 Gallery。
activity_main.xml:
接著是 Gallery 的 Adapter,這裡重寫 BaseAdapter,由於只顯示一張圖片,就不再額外寫佈局了。
MeiziAdapter.java:
/** * Created by Jay on 2015/10/16 0016. */ public class MeiziAdapter extends BaseAdapter{ private Context mContext; private int[] mData; public MeiziAdapter() { } public MeiziAdapter(Context mContext,int[] mData) { this.mContext = mContext; this.mData = mData; } @Override public int getCount() { return mData.length; } @Override public Object getItem(int position) { return mData[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imgMezi = new ImageView(mContext); imgMezi.setImageResource(mData[position]); //創建一個ImageView imgMezi.setScaleType(ImageView.ScaleType.FIT_XY); //設置imgView的縮放類型 imgMezi.setLayoutParams(new Gallery.LayoutParams(250, 250)); //為imgView設置布局參數 TypedArray typedArray = mContext.obtainStyledAttributes(R.styleable.Gallery); imgMezi.setBackgroundResource(typedArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0)); return imgMezi; } }
最後是 Activity,邏輯很簡單:為 Gallery 設置 onSelected 事件,點擊按鈕後把當前選中的 position 傳給下一頁。
MainActivity.java:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener { private Context mContext; private ImageView img_choose; private Button btn_choose; private Gallery gay_choose; private int index = 0; private MeiziAdapter mAdapter = null; private int[] imageIds = new int[] { R.mipmap.pre1, R.mipmap.pre2, R.mipmap.pre3, R.mipmap.pre4, R.mipmap.pre5, R.mipmap.pre6, R.mipmap.pre7, R.mipmap.pre8, R.mipmap.pre9, R.mipmap.pre10, R.mipmap.pre11, R.mipmap.pre12, R.mipmap.pre13, R.mipmap.pre14, R.mipmap.pre15, R.mipmap.pre16, R.mipmap.pre17, R.mipmap.pre18, R.mipmap.pre19, R.mipmap.pre20, R.mipmap.pre21 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = MainActivity.this; bindViews(); } private void bindViews() { img_choose = (ImageView) findViewById(R.id.img_choose); btn_choose = (Button) findViewById(R.id.btn_choose); gay_choose = (Gallery) findViewById(R.id.gay_choose); mAdapter = new MeiziAdapter(mContext, imageIds); gay_choose.setAdapter(mAdapter); gay_choose.setOnItemSelectedListener(this); btn_choose.setOnClickListener(this); } @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { img_choose.setImageResource(imageIds[position]); index = position; } @Override public void onNothingSelected(AdapterView parent) { } @Override public void onClick(View v) { Intent it = new Intent(mContext,CaClothes.class); Bundle bundle = new Bundle(); bundle.putCharSequence(num, Integer.toString(index)); it.putExtras(bundle); startActivity(it); } }
接著是擦除頁,佈局簡單,FrameLayout 疊放前後兩個 ImageView:
activity_caclothes.xml:
<framelayout android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="https://schemas.android.com/apk/res/android"></framelayout>
Java 部分如下:
CaClothes.java:
/** * Created by Jay on 2015/10/16 0016. */ public class CaClothes extends AppCompatActivity implements View.OnTouchListener { private ImageView img_after; private ImageView img_before; private Bitmap alterBitmap; private Canvas canvas; private Paint paint; private Bitmap after; private Bitmap before; private int position; int[] imageIds1 = new int[] { R.mipmap.pre1, R.mipmap.pre2, R.mipmap.pre3, R.mipmap.pre4, R.mipmap.pre5, R.mipmap.pre6, R.mipmap.pre7, R.mipmap.pre8, R.mipmap.pre9, R.mipmap.pre10, R.mipmap.pre11, R.mipmap.pre12, R.mipmap.pre13, R.mipmap.pre14, R.mipmap.pre15, R.mipmap.pre16, R.mipmap.pre17, R.mipmap.pre18, R.mipmap.pre19, R.mipmap.pre20, R.mipmap.pre21 }; int[] imageIds2 = new int[] { R.mipmap.after1, R.mipmap.after2, R.mipmap.after3, R.mipmap.after4, R.mipmap.after5, R.mipmap.after6, R.mipmap.after7, R.mipmap.after8, R.mipmap.after9, R.mipmap.after10, R.mipmap.after11, R.mipmap.after12, R.mipmap.after13, R.mipmap.after14, R.mipmap.after15, R.mipmap.after16, R.mipmap.after17, R.mipmap.after18, R.mipmap.after19, R.mipmap.after20, R.mipmap.after21 }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_caclothes); Bundle bd = getIntent().getExtras(); position = Integer.parseInt(bd.getString(num)); bindViews(); } private void bindViews() { img_after = (ImageView) findViewById(R.id.img_after); img_before = (ImageView) findViewById(R.id.img_before); BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inSampleSize = 1; after = BitmapFactory.decodeResource(getResources(), imageIds2[position], opts); before = BitmapFactory.decodeResource(getResources(), imageIds1[position], opts); //定義出來的是只讀圖片 alterBitmap = Bitmap.createBitmap(before.getWidth(), before.getHeight(), Bitmap.Config.ARGB_4444); canvas = new Canvas(alterBitmap); paint = new Paint(); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStrokeJoin(Paint.Join.ROUND); paint.setStrokeWidth(5); paint.setColor(Color.BLACK); paint.setAntiAlias(true); canvas.drawBitmap(before, new Matrix(), paint); img_after.setImageBitmap(after); img_before.setImageBitmap(before); img_before.setOnTouchListener(this); } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: int newX = (int) event.getX(); int newY = (int) event.getY(); //setPixel方法是將某一個像素點設置成一個顏色,而這裡我們把他設置成透明 //另外通過嵌套for循環將手指觸摸區域的20*20個像素點設置為透明 for (int i = -20; i < 20; i++) { for (int j = -20; j < 20; j++) { if (i + newX >= 0 && j + newY >= 0 && i + newX < before.getWidth() && j + newY < before.getHeight()) alterBitmap.setPixel(i + newX, j + newY, Color.TRANSPARENT); } } img_before.setImageBitmap(alterBitmap); break; } return true; } }
整體代碼並不晦澀,理解起來相當直觀。多看多想,繪圖這塊自然就上手了。
Android Lollipop 勿擾模式設計解析
勿擾模式背景 Android Lollipop 引入了名為 Interruptions 的通知管控機制,中文常稱為勿擾模式。它允許使用者決定哪些通知、來電與提醒可以打擾自
Android 登入、註冊與找回密碼功能設計實作
本文分享一套登入、找回密碼、註冊功能的實作,供參考。1. 資料庫設計這裡用了兩張表:一張存使用者資訊(帳號、密碼、手機號等,欄位可自行擴充),另一張存「上次登入的使用者」
從零打造 Android 效能測試工具:架構、前端與核心實作筆記
前言 近來在 TesterHome 上看了不少關於效能測試的文章。看別人的東西终究是別人的,唯有親手寫一遍,才能真正體會其中的細節。雖然常說不要重複造輪子,但這類基礎工具
仿騰訊手機管家小火箭發射動效:自訂 Toast + Service 實作
之前分析過系統 Toast 的原始碼,這篇拿來做個延伸練習:自訂一個 Toast 風格的懸浮火箭,做出騰訊手機管家那種拖到右下角松手發射的效果。若只看程式碼有點吃力,建議