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

自訂 View 實作:可編輯、可選取的圓形頭像裁剪控件

編輯:關於 Android 程式設計

在 Android 開發中,幾乎每個 App 都有讓使用者上傳頭像的需求。頭像的形狀五花八門,有的採用方形、有的圓角矩形、有的則是圓形。無論哪一種,我們都需要一個能處理圖片的自訂 View,把傳入的圖片經過使用者選取區域後,裁剪成特定的形狀。

常見的做法有兩種:一是在圖片上畫出一個矩形區域來表示選取範圍;另一則是透過雙指縮放、拖曳圖片來選取。由於圓形頭像更適合直接改變圖片本身,因此本範例採用「縮放平移圖片、以固定圓形區域裁剪」的思路。

圓形選取區域的大小可自由調整。

這個自訂 View 在繪製上分為三個部分:背景圖片、半透明蒙層,以及中央的亮色(透明)區域。以下直接附上程式碼:

public class RoundEditImageView extends View {
    private Bitmap bitmap;
    RectF clipBounds, dst, src;
    Paint clearPaint;
    private int w, h;
    private float radius = 150f;      // 選區半徑
    private RectF circleBounds;       // 圓形選區的邊界
    private float max_scale = 2.0f;   // 最大放大倍數
    private float distance;           // 雙指間距
    private float x0, y0;
    private boolean doublePoint;

    public RoundEditImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    public RoundEditImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public RoundEditImageView(Context context) {
        super(context);
        init();
    }

    private void init() {
        clearPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        clearPaint.setColor(Color.GRAY);
        clearPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (bitmap != null) {
            canvas.drawBitmap(bitmap, null, dst, null);
        }
        // 保存圖層,以免清除時連同 bitmap 一起被清掉
        int count = canvas.saveLayer(clipBounds, null, Canvas.ALL_SAVE_FLAG);
        canvas.drawColor(0x80000000);
        // 清除半透明黑色,留下一個透明圓
        canvas.drawCircle(w / 2, h / 2, radius, clearPaint);
        canvas.restoreToCount(count);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        this.w = w;
        this.h = h;
        clipBounds = new RectF(0, 0, w, h);
        float l, r, t, b;
        if (bitmap != null) {
            // 依長寬比以 fitCenter 方式初始化圖片
            if (w / (float) h > bitmap.getWidth() / (float) bitmap.getHeight()) {
                float w_ = h * bitmap.getWidth() / (float) bitmap.getHeight();
                l = w / 2f - w_ / 2f;
                r = w / 2f + w_ / 2f;
                t = 0;
                b = h;
            } else {
                float h_ = w * bitmap.getHeight() / (float) bitmap.getWidth();
                l = 0;
                r = w;
                t = h / 2f - h_ / 2f;
                b = h / 2f + h_ / 2f;
            }
            dst = new RectF(l, t, r, b);  // 用於縮放平移
            src = new RectF(l, t, r, b);  // 保存初始狀態
            max_scale = Math.max(max_scale, bitmap.getWidth() / src.width());
        }
        circleBounds = new RectF(w / 2 - radius, h / 2 - radius, w / 2 + radius, h / 2 + radius);
    }

    public void setImageBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
        invalidate();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent e) {
        if (e.getPointerCount() > 2) {
            return false;   // 不接受多於兩指的事件
        } else if (e.getPointerCount() == 2) {
            doublePoint = true;
            handleDoubleMove(e);
        } else {
            switch (e.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    x0 = e.getX();
                    y0 = e.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (doublePoint) break;
                    float x = e.getX();
                    float y = e.getY();
                    float w = dst.width();
                    float h = dst.height();
                    // 不允許拖過圓形區域,避免圓內出現空白
                    dst.left += x - x0;
                    if (dst.left > circleBounds.left) {
                        dst.left = circleBounds.left;
                    } else if (dst.left < circleBounds.right - w) {
                        dst.left = circleBounds.right - w;
                    }
                    dst.right = dst.left + w;
                    dst.top += y - y0;
                    if (dst.top > circleBounds.top) {
                        dst.top = circleBounds.top;
                    } else if (dst.top < circleBounds.bottom - h) {
                        dst.top = circleBounds.bottom - h;
                    }
                    dst.bottom = dst.top + h;
                    x0 = x;
                    y0 = y;
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    doublePoint = false;
                    break;
            }
        }
        return true;
    }

    private void handleDoubleMove(MotionEvent e) {
        switch (e.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_POINTER_DOWN:
                distance = sqrt(e);
                break;
            case MotionEvent.ACTION_MOVE:
                scale(e);
                break;
        }
    }

    private void scale(MotionEvent e) {
        float dis = sqrt(e);
        // 以雙指中心作為縮放支點
        float pX = e.getX(0) / 2f + e.getX(1) / 2f;
        float pY = e.getY(0) / 2f + e.getY(1) / 2f;
        float scale = dis / distance;
        float w = dst.width();
        float h = dst.height();
        // 無法縮小到比選區還小,或到達最大倍數
        if (w * scale < radius * 2 || h * scale < radius * 2 || w * scale > src.width() * max_scale) {
            return;
        }
        dst.left = (dst.left - pX) * scale + pX;
        dst.right = (dst.right - pX) * scale + pX;
        dst.top = (dst.top - pY) * scale + pY;
        dst.bottom = (dst.bottom - pY) * scale + pY;
        // 縮放同樣不允許使圓形區域空白
        if (dst.left > circleBounds.left) {
            dst.left = circleBounds.left;
            dst.right = dst.left + w * scale;
        } else if (dst.right < circleBounds.right) {
            dst.right = circleBounds.right;
            dst.left = dst.right - w * scale;
        }
        if (dst.top > circleBounds.top) {
            dst.top = circleBounds.top;
            dst.bottom = dst.top + h * scale;
        } else if (dst.bottom < circleBounds.bottom) {
            dst.bottom = circleBounds.bottom;
            dst.top = dst.bottom - h * scale;
        }
        invalidate();
        distance = dis;
    }

    private float sqrt(MotionEvent e) {
        return (float) Math.sqrt((e.getX(0) - e.getX(1)) * (e.getX(0) - e.getX(1))
                + (e.getY(0) - e.getY(1)) * (e.getY(0) - e.getY(1)));
    }

    // 產生目前選區指定大小的圓形 bitmap
    public Bitmap extractBitmap(int width) {
        Bitmap outBitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(outBitmap);
        Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setColor(Color.GRAY);
        canvas.drawCircle(width / 2, width / 2, width / 2, p);
        float scale = dst.width() / bitmap.getWidth();
        int w = (int) (circleBounds.width() / scale);
        int l = (int) ((circleBounds.left - dst.left) / scale);
        int r = l + w;
        int t = (int) ((circleBounds.top - dst.top) / scale);
        int b = t + w;
        Rect resRect = new Rect(l, t, r, b);
        Paint paint = new Paint();
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, resRect, canvas.getClipBounds(), paint);
        return outBitmap;
    }
}

Activity 中的用法

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select_header);
    RoundEditImageView imageView = (RoundEditImageView) findViewById(R.id.roundEditImageView1);
    bitmap = BitmapFactory.decodeFile(imagePath);
    imageView.setImageBitmap(bitmap);
}

@Override
public void onClick(View v) {
    // 產生一張 300*300 的目前亮圓形中的圖片
    Bitmap result = imageView.extractBitmap(300);
    // 壓縮成 png
    FileOutputStream out = new FileOutputStream(new File(filePath));
    result.compress(Bitmap.CompressFormat.PNG, 100, out);
    // 上傳與顯示 ...
}

這個需求是模仿 QQ 的頭像選取體驗,核心思路就是透過 dst 矩形的縮放與平移來控制顯示範圍,再以固定圓形區域完成裁剪,最後輸出指定尺寸的圓形頭像。

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