Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ImageView 圖片縮放與旋轉:SeekBar 即時控制實作

編輯:關於 Android 程式設計

做圖片瀏覽器時,縮放與旋轉是最基本的兩個操作。這篇用兩個 SeekBar 分別控制寬高與旋轉角度,順便把「改 LayoutParams」與「改 Bitmap 矩陣」這兩種思路的差別講清楚。

一、兩種縮放思路

第一種是改動 ImageView 的容器尺寸。因為 ImageView 設定了 scaleType="fitCenter",圖片會自動貼合框架,所以只要改變框架大小,圖片視覺上就跟着縮放了。這種做法成本低,因為沒有重新解碼或重繪 Bitmap。

第二種是直接對 Bitmap 做矩陣變換,產生一張新的圖。旋轉就必須走這條路,但要注意它會佔用額外記憶體。

二、版面配置

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="300dp"
        android:layout_height="200dp"
        android:scaleType="fitCenter"
        android:src="@drawable/photo" />

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="圖片縮放" />

    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="480"
        android:progress="300" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="圖片旋轉" />

    <SeekBar
        android:id="@+id/seekBar2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="360"
        android:progress="0" />

</LinearLayout>

三、MainActivity

package com.example.imageview_demo03;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

@SuppressLint("NewApi")
public class MainActivity extends ActionBarActivity implements OnSeekBarChangeListener {

    // 縮放的下限寬度
    private int minWidth = 80;

    private ImageView imageView;
    private SeekBar seekBar1;
    private SeekBar seekBar2;
    private TextView textView1;
    private TextView textView2;

    // 矩陣類別,用於對圖像做旋轉
    private Matrix matrix = new Matrix();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.imageView);
        seekBar1  = (SeekBar)   findViewById(R.id.seekBar1);
        seekBar2  = (SeekBar)   findViewById(R.id.seekBar2);
        textView1 = (TextView)  findViewById(R.id.textview1);
        textView2 = (TextView)  findViewById(R.id.textview2);

        seekBar1.setOnSeekBarChangeListener(this);
        seekBar2.setOnSeekBarChangeListener(this);

        // 取得螢幕尺寸,把縮放上限設為螢幕寬度
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        seekBar1.setMax(displayMetrics.widthPixels - minWidth);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (seekBar.getId() == R.id.seekBar1) {
            // 實際寬度 = 進度 + 下限
            int mwidth  = progress + minWidth;
            int mheight = (int) (2 * mwidth / 3);   // 維持 3:2 比例

            // 改動 ImageView 的框架尺寸,圖片會因 fitCenter 而跟著縮放
            imageView.setLayoutParams(
                    new LinearLayout.LayoutParams(mwidth, mheight));

            textView1.setText("圖片寬度:" + mwidth + "\t圖片高度:" + mheight);

        } else if (seekBar.getId() == R.id.seekBar2) {
            // 方案一:ImageView 內建的 setRotation()
            // 優點是不額外配置記憶體
            // 缺點是旋轉後超出框架的部分會覆蓋到下方視圖
            // imageView.setRotation(progress);

            // 方案二:取出原圖做矩陣旋轉後重新塞回 ImageView
            // 可限制在框架內,但每次都產生新 Bitmap,較耗記憶體
            Bitmap bitmap = ((BitmapDrawable)
                    getResources().getDrawable(R.drawable.photo)).getBitmap();

            matrix.setRotate(progress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), matrix, true);

            imageView.setImageBitmap(bitmap);
            textView2.setText("圖片旋轉 " + progress + " 度");
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) { }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) { }
}

四、幾個值得改進的地方

  • 旋轉造成的記憶體問題。範例在 onProgressChanged() 中每次都重新產生一張 Bitmap,而拖动 SeekBar 每秒可觸發數十次,舊的 Bitmap 又沒有 recycle(),在低端機上很快也會 OOM。實務上應該改用 imageView.setRotation(progress) 或 View.setPivotX() 搭配屬性動畫,讓 GPU 處理變換。
  • 應該保留原始 Bitmap。目前每次旋轉都從資源重新解碼,累加誤差與效能損耗都不划算。正確做法是在 onCreate() 中讀取一次原圖存成成員變數,後續基於它做變換。
  • 縮放比例寫死了。2 * mwidth / 3 是硬編碼的 3:2,換一張不同比例的圖就會變形。應改為讀取原圖實際寬高再換算。
  • API 相容性。getResources().getDrawable() 在 API 23 後不建議使用,ActionBarActivity 也已由 AppCompatActivity 取代。新專案建議採用 ContextCompat.getDrawable() 與現代的 AppCompat 基底類別。

如果文中有不妥之處,或你有更好的做法,歡迎交流。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved