1. 程式人生 > >Android 圓角圓形ImageView(超簡單實現)

Android 圓角圓形ImageView(超簡單實現)

前言:今天偶然看到我之前寫過的一篇部落格 Android專案中遇到的坑之(Android圓角圓形圖 一),我在想,這不就是在模仿ImageView麼,我為什麼要模仿,直接拿來用不是更好麼?我能直接在ImageView的原始碼上去改改程式碼? 於是就有了下面這篇文章了。

先上一張效果圖:

這裡寫圖片描述

效果還是很不錯的,程式碼更簡單哦~~~

但凡搞過android的童鞋一定都知道ImageView,既然ImageView已經處理好了各種縮放問題,然後相容性就更不用說了是吧,好歹別人也是一個系統元件,那顯示圖片等一系列的任務ImageView都幫我們實現好了,我們無非就是在它的基礎上新增一個顯示圓角圓形的功能,所以我們看看它的原始碼..

其它的原始碼我們就不看了,我們重點看它的onDraw方法:

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mDrawable == null) {
            return; // couldn't resolve the URI
        }

        if (mDrawableWidth == 0 || mDrawableHeight == 0) {
            return;     // nothing to draw (empty bounds)
} if (mDrawMatrix == null && mPaddingTop == 0 && mPaddingLeft == 0) { mDrawable.draw(canvas); } else { final int saveCount = canvas.getSaveCount(); canvas.save(); if (mCropToPadding) { final int scrollX = mScrollX; final
int scrollY = mScrollY; canvas.clipRect(scrollX + mPaddingLeft, scrollY + mPaddingTop, scrollX + mRight - mLeft - mPaddingRight, scrollY + mBottom - mTop - mPaddingBottom); } canvas.translate(mPaddingLeft, mPaddingTop); if (mDrawMatrix != null) { canvas.concat(mDrawMatrix); } mDrawable.draw(canvas); canvas.restoreToCount(saveCount); } }

程式碼還是很簡單的,相比小夥伴都看得懂,我簡單的說一下,當我們設定了ImageView的scaleType後,imageview會通過演算法依據我們傳遞的scaletype型別轉換成Matrix物件,我們可以看到這麼一段程式碼:

 if (mDrawMatrix != null) {
                canvas.concat(mDrawMatrix);
            }

轉換成Matrix物件後,直接設給了當前畫布,然後把我們傳遞給ImageView的圖片顯示出來:

mDrawable.draw(canvas);
            canvas.restoreToCount(saveCount);

是的,沒錯就是這麼簡單~~~

然後我們需要做什麼呢?

首先定一個attrs檔案:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="RoundImageView">
        <attr name="type" format="enum">
            <enum name="circle" value="1"/>
            <enum name="round" value="2"/>
        </attr>
        <attr name="radius" format="dimension"/>ssss
    </declare-styleable>
</resources>

首先我們定義一個view叫RoundImageView,然後繼承ImageView,重寫其構造方法:

public class RoundImageView extends ImageView {
    /**
     * 圓形模式
     */
    private static final int MODE_CIRCLE = 1;
    /**
     * 普通模式
     */
    private static final int MODE_NONE = 0;
    /**
     * 圓角模式
     */
    private static final int MODE_ROUND = 2;
    private Paint mPaint;
    private int currMode = 0;
    /**
     * 圓角半徑
     */
    private int currRound = dp2px(10);

    public RoundImageView(Context context) {
        super(context);
        initViews();
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        obtainStyledAttrs(context, attrs, defStyleAttr);
        initViews();
    }

    private void obtainStyledAttrs(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView, defStyleAttr, 0);
        currMode = a.hasValue(R.styleable.RoundImageView_type) ? a.getInt(R.styleable.RoundImageView_type, MODE_NONE) : MODE_NONE;
        currRound = a.hasValue(R.styleable.RoundImageView_radius) ? a.getDimensionPixelSize(R.styleable.RoundImageView_radius, currRound) : currRound;
        a.recycle();
    }
}

然後就是重寫onMeasure方法了,我要處理的就是當模式為圓形的時候強制把控制元件的寬高保持一致:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        /**
         * 當模式為圓形模式的時候,我們強制讓寬高一致
         */
        if (currMode == MODE_CIRCLE) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int result = Math.min(getMeasuredHeight(), getMeasuredWidth());
            setMeasuredDimension(result, result);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

好了,然後就是重寫我們的onDraw方法了,我們直接把ImageView的程式碼拷貝過來,然後稍稍改一下:

 @Override
    protected void onDraw(Canvas canvas) {
        Drawable mDrawable = getDrawable();
        Matrix mDrawMatrix = getImageMatrix();
        if (mDrawable == null) {
            return; // couldn't resolve the URI
        }

        if (mDrawable.getIntrinsicWidth() == 0 || mDrawable.getIntrinsicHeight() == 0) {
            return;     // nothing to draw (empty bounds)
        }

        if (mDrawMatrix == null && getPaddingTop() == 0 && getPaddingLeft() == 0) {
            mDrawable.draw(canvas);
        } else {
            final int saveCount = canvas.getSaveCount();
            canvas.save();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                if (getCropToPadding()) {
                    final int scrollX = getScrollX();
                    final int scrollY = getScrollY();
                    canvas.clipRect(scrollX + getPaddingLeft(), scrollY + getPaddingTop(),
                            scrollX + getRight() - getLeft() - getPaddingRight(),
                            scrollY + getBottom() - getTop() - getPaddingBottom());
                }
            }
            canvas.translate(getPaddingLeft(), getPaddingTop());
            if (currMode == MODE_CIRCLE) {//當為圓形模式的時候
                Bitmap bitmap = drawable2Bitmap(mDrawable);
                mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
                canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, mPaint);
            } else if (currMode == MODE_ROUND) {//當為圓角模式的時候
                Bitmap bitmap = drawable2Bitmap(mDrawable);
                mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
                canvas.drawRoundRect(new RectF(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()),
                        currRound, currRound, mPaint);
            } else {
                if (mDrawMatrix != null) {
                    canvas.concat(mDrawMatrix);
                }
                mDrawable.draw(canvas);
            }
            canvas.restoreToCount(saveCount);
        }
    }

好啦~~ 因為我們寫到的程式碼就只有幾行:

if (currMode == MODE_CIRCLE) {//當為圓形模式的時候
                Bitmap bitmap = drawable2Bitmap(mDrawable);
                mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
                canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, mPaint);
            } else if (currMode == MODE_ROUND) {//當為圓角模式的時候
                Bitmap bitmap = drawable2Bitmap(mDrawable);
                mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
                canvas.drawRoundRect(new RectF(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()),
                        currRound, currRound, mPaint);
            }

就是當模式為circle跟round的時候,給畫筆設定一個bitmapshader(bitmapshader不懂的童鞋自己上api或網上看看其用法)然後用當前canvas畫一個圓或者圓角矩形。

然後你就可以用起來了:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.yasin.roundimageview.MainActivity"
    android:orientation="vertical"
    >

    <com.yasin.roundimageview.RoundImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/test"
        android:scaleType="fitXY"
        />
    <com.yasin.roundimageview.RoundImageView
        android:layout_marginTop="10dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/test"
        android:scaleType="centerCrop"
        app:type="round"
        />
    <com.yasin.roundimageview.RoundImageView
        android:layout_marginTop="10dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/test"
        app:type="circle"
        android:scaleType="fitXY"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        >
        <com.yasin.roundimageview.RoundImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@color/colorAccent"
            />
        <com.yasin.roundimageview.RoundImageView
            android:layout_marginLeft="10dp"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@color/colorAccent"
            app:type="round"
            />
        <com.yasin.roundimageview.RoundImageView
            android:layout_marginLeft="10dp"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@color/colorAccent"
            app:type="circle"
            />
    </LinearLayout>
</LinearLayout>

好啦~~!! 是不是覺得soeasy呢??

最後貼上RoundImageView全部程式碼:

package com.yasin.roundimageview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;


/**
 * Created by leo on 17/3/14.
 */

public class RoundImageView extends ImageView {
    /**
     * 圓形模式
     */
    private static final int MODE_CIRCLE = 1;
    /**
     * 普通模式
     */
    private static final int MODE_NONE = 0;
    /**
     * 圓角模式
     */
    private static final int MODE_ROUND = 2;
    private Paint mPaint;
    private int currMode = 0;
    /**
     * 圓角半徑
     */
    private int currRound = dp2px(10);

    public RoundImageView(Context context) {
        super(context);
        initViews();
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        obtainStyledAttrs(context, attrs, defStyleAttr);
        initViews();
    }

    private void obtainStyledAttrs(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView, defStyleAttr, 0);
        currMode = a.hasValue(R.styleable.RoundImageView_type) ? a.getInt(R.styleable.RoundImageView_type, MODE_NONE) : MODE_NONE;
        currRound = a.hasValue(R.styleable.RoundImageView_radius) ? a.getDimensionPixelSize(R.styleable.RoundImageView_radius, currRound) : currRound;
        a.recycle();
    }

    private void initViews() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        /**
         * 當模式為圓形模式的時候,我們強制讓寬高一致
         */
        if (currMode == MODE_CIRCLE) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int result = Math.min(getMeasuredHeight(), getMeasuredWidth());
            setMeasuredDimension(result, result);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable mDrawable = getDrawable();
        Matrix mDrawMatrix = getImageMatrix();
        if (mDrawable == null) {
            return; // couldn't resolve the URI
        }

        if (mDrawable.getIntrinsicWidth() == 0 || mDrawable.getIntrinsicHeight() == 0) {
            return;     // nothing to draw (empty bounds)
        }

        if (mDrawMatrix == null && getPaddingTop() == 0 && getPaddingLeft() == 0) {
            mDrawable.draw(canvas);
        } else {
            final int saveCount = canvas.getSaveCount();
            canvas.save();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                if (getCropToPadding()) {
                    final int scrollX = getScrollX();
                    final int scrollY = getScrollY();
                    canvas.clipRect(scrollX + getPaddingLeft(), scrollY + getPaddingTop(),
                            scrollX + getRight() - getLeft() - getPaddingRight(),
                            scrollY + getBottom() - getTop() - getPaddingBottom());
                }
            }
            canvas.translate(getPaddingLeft(), getPaddingTop());
            if (currMode == MODE_CIRCLE) {//當為圓形模式的時候
                Bitmap bitmap = drawable2Bitmap(mDrawable);
                mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
                canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, mPaint);
            } else if (currMode == MODE_ROUND) {//當為圓角模式的時候
                Bitmap bitmap = drawable2Bitmap(mDrawable);
                mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
                canvas.drawRoundRect(new RectF(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()),
                        currRound, currRound, mPaint);
            } else {
                if (mDrawMatrix != null) {
                    canvas.concat(mDrawMatrix);
                }
                mDrawable.draw(canvas);
            }
            canvas.restoreToCount(saveCount);
        }
    }

    /**
     * drawable轉換成bitmap
     */
    private Bitmap drawable2Bitmap(Drawable drawable) {
        if (drawable == null) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        //根據傳遞的scaletype獲取matrix物件,設定給bitmap
        Matrix matrix = getImageMatrix();
        if (matrix != null) {
            canvas.concat(matrix);
        }
        drawable.draw(canvas);
        return bitmap;
    }

    private int dp2px(float value) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, getResources().getDisplayMetrics());
    }
}