android Matrix工具的使用

來源:互聯網
上載者:User

Matrix工具類是對圖形進行特效處理。

Matrix 是一個矩陣工具類,本身不能對圖形進行變換,可以與其他API來結合使用。

擷取Matrix對象,可以直接建立,可以從其他封裝了Matrix類中擷取,Transformation裡面就封裝了Matrix對象。

調用Matrix對象的方法可以對圖形映像進行平移,縮放,旋轉,傾斜等。

需要將程式對Matrix所做的變換應用到指定映像或組件上面。

下面是一個Matrix使用方法的例子,利用按鍵來控制Bitmap的傾斜和縮放。

class MyView extends View {/**源圖*/private Bitmap bitmap;/**Matrix對象*/private Matrix matrix = new Matrix();/**傾斜度*/public float ox = 0.0f;/**縮放度*/public float scale = 1.0f;/**源圖尺寸*/private int width, height;/**縮放還是傾斜*/private boolean isScale = false;public MyView(Context context, AttributeSet attrs) {super(context, attrs);//得到位元影像bitmap = ((BitmapDrawable) this.getResources().getDrawable(R.drawable.ic_launcher)).getBitmap();width = bitmap.getWidth();height = bitmap.getHeight();//按鍵控制,首先要擷取到焦點this.setFocusable(true);}@SuppressLint("DrawAllocation")@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);//重設Matrix、傾斜狀態時恢複到源圖再進行縮放matrix.reset();if(isScale){//x/y軸同比放大縮小matrix.setScale(scale, scale);}else{matrix.setSkew(ox,ox);}//得到新圖Bitmap b = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);//將程式對Matrix所做的變換應用到指定映像或組件上面canvas.drawBitmap(b, matrix, null);}@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {switch (keyCode) {case KeyEvent.KEYCODE_DPAD_LEFT://傾斜isScale=false;ox+=0.1;//重新整理介面,view類也有該方法postInvalidate();break;case KeyEvent.KEYCODE_DPAD_RIGHT://傾斜isScale=false;ox-=0.1;postInvalidate();break;case KeyEvent.KEYCODE_DPAD_UP://放大isScale=true;if(scale<2.0){scale+=0.1;}postInvalidate();break;case KeyEvent.KEYCODE_DPAD_DOWN://縮小isScale=true;if(scale>0.5){scale-=0.1;}postInvalidate();break;default:break;}return super.onKeyDown(keyCode, event);}}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.