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

運用 ShapeDrawable 打造 Android 放大鏡效果

編輯:關於 Android 程式設計

在 Android 上想實作局部放大的效果,例如在畫面中加入一塊類似放大鏡的區域,ShapeDrawable 是一個相當優雅而靈活的選擇。它的優勢在於兩點:其一,建構時可以指定要描繪的形狀;其二,可以透過 shape.getPaint().setShader() 指定 Shader,而 Shader 能接受一張圖片與一個 Matrix。有了這兩個特性,放大效果便能自然實現。

實作程式碼

以一個圓形(OvalShape)為例,透過 BitmapShader 搭配 Matrix 做平移與縮放,即可畫出放大後的影像:

float scale = 1.2f;

int cx = 224;
int cy = 357;
int r = 200;

// 指定形狀創建一個 ShapeDrawable
ShapeDrawable shape=new ShapeDrawable(new OvalShape());
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.bg1);
BitmapShader bs = new BitmapShader(bm, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

Matrix m = new Matrix();
m.setTranslate(r-cx, r-cy);
m.postScale(scale, scale);
bs.setLocalMatrix(m);   // 圖形變換可以在這裡實現,包括區域指定

// 為 ShapeDrawable 設置 Shader
shape.getPaint().setShader(bs);

// 指定描畫目標位置
shape.setBounds((int)(cx-r*scale),(int)(cy-r*scale),(int)(cx+r*scale),(int)(cy+r*scale));
canvas.drawBitmap(bm, 0, 0, null);
shape.draw(canvas);

重點說明

程式中的 scale 控制放大倍率,cx、cy 為放大中心座標,r 為半徑。Matrix 先透過 setTranslate 將原圖對齊到以放大中心為基準的位置,再用 postScale 進行縮放,最後由 setLocalMatrix 套用至 Shader。由於 Shader 直接綁定在 ShapeDrawable 的 Paint 上,只要改變 Matrix 的平移與縮放參數,就能靈活決定放大哪一塊區域以及放大的程度。

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