在Android中實現圖片縮放和旋轉

openkk 12年前發布 | 26K 次閱讀 Android Android開發 移動開發

btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            i = ++i;            
            ImageView view = (ImageView)findViewById(R.id.imgView); 
           // 1、首先加載要操作的圖片
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.aa);
            //2、得到以上加載圖片的高度跟寬度
            int height = bitmap.getHeight(); 
            int width = bitmap.getWidth();
            //3、定義要縮放成最終的圖片高度跟寬度
            int nHeight = 150; 
            int nWidth = 180;
            //4、計算縮放比例
            float scaleWidth = ((float) nWidth)/width; 
            float scaleHeight = ((float) nHeight)/height;
            //5、創建Matrix對象 Matrix是在Android中用于操作圖像的類
            Matrix matrix = new Matrix();
            //6、使用Matrix對象跟縮放比例實現縮放圖片
            matrix.postScale(scaleWidth, scaleHeight);
           //同樣的,圖片旋轉只需要通過Matrix改變圖片角度即可,生成圖片跟7相同。
            Log.i("chens", "======i======"+i);
            if (i % 2 ==0 ) {
                matrix.postRotate(60);
            }else {
                matrix.postRotate(0);
            }

            //7、生成縮放后的圖片
            Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,width, height, matrix, true);
            view.setImageBitmap(resizedBitmap);

        }
    });</pre><br />
 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!