標籤:
本文實現Android中的圖片的縮放效果
首先設計布局:
<LinearLayout 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:orientation="vertical" tools:context=".MainActivity" > <ImageView android:id="@+id/iv_1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/iv_2" android:layout_width="wrap_content" android:layout_height="wrap_content" /></LinearLayout>
邏輯代碼如下:
public class MainActivity extends Activity { private ImageView iv1; private ImageView iv2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv1 = (ImageView) findViewById(R.id.iv_1); iv2 = (ImageView) findViewById(R.id.iv_2); // 設定第一個bitmap的表徵圖 Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); iv1.setImageBitmap(bitmap1); // 建立一個bitmap Bitmap alterBitmap = Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight(), bitmap1.getConfig()); // 以alterBitmap為模板建立畫布 Canvas canvas = new Canvas(alterBitmap); // 建立畫筆並設定屬性 Paint paint = new Paint(); paint.setColor(Color.BLACK); //建立矩陣並設定縮放值 Matrix matrix = new Matrix(); matrix.setValues(new float[] { 0.5f, 0, 0, 0, 1, 0, 0, 0, 1 }); //設定畫布 canvas.drawBitmap(bitmap1, matrix, paint); iv2.setImageBitmap(alterBitmap); }}
如果你對矩陣的設定不清楚,還可以使用下列api提供的方法替換上面標記部分的代碼:
matrix.setScale(0.5f, 1);
最後運行項目效果如下:
Android 圖片的縮放