最近被問到如何將圖片轉(zhuǎn)為圓形顯示出來,當(dāng)時腦袋一蒙彤悔,想著圖片加載框架(如glide等)不都有這個功能了么嘉抓?但感覺自己確實(shí)沒有特別關(guān)注這方面的內(nèi)容,就去學(xué)習(xí)整理了一波晕窑,不說了抑片,直接上代碼:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;
import java.io.IOException;
/**
* 圖片圓角化
*/
public class RoundImageView extends ImageView {
private Bitmap mBitmap;
private Paint mPaint;
public RoundImageView(Context context) {
this(context, null);
}
public RoundImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
//初始化畫筆paint
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
}
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap == null || mBitmap.isRecycled()) {
try {
//直接網(wǎng)上找張圖片,放到assets目錄下
mBitmap = BitmapFactory.decodeStream(getContext().getAssets().open("avatar.jpeg"));
} catch (IOException e) {
e.printStackTrace();
}
}
//畫出圓形圖片就這三個方法
// shaderRound(canvas);
clipRound(canvas);
// xfermodRound(canvas);
}
/**
* 方式一:離屏混合模式實(shí)現(xiàn)
*/
private void xfermodRound(Canvas canvas) {
//新圖層:離屏繪制杨赤,restore后才將內(nèi)容顯示到屏幕上
canvas.saveLayer(0, 0, getWidth(), getHeight(), mPaint);
//寬高自己指定敞斋,這里測試暫時用控件默認(rèn)寬高
canvas.drawCircle(getWidth()/2, getHeight()/2, getHeight()/2, mPaint);
//設(shè)置混合模式為SRC_IN
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(mBitmap,null, new Rect(0, 0, getWidth(), getHeight()), mPaint);
canvas.restore();
}
/**
* 方式2:剪切路徑實(shí)現(xiàn),缺點(diǎn)是不能抗鋸齒
*/
private void clipRound(Canvas canvas) {
canvas.save();
Path path = new Path();
path.addCircle(getWidth() / 2, getWidth() / 2, getWidth() / 2, Path.Direction.CW);
canvas.clipPath(path);
canvas.drawBitmap(mBitmap, null, new Rect(0, 0, getWidth(), getHeight()), mPaint);
canvas.restore();
}
/**
* 方式三:shader實(shí)現(xiàn)疾牲,跟方式一無大的差別
*/
private void shaderRound(Canvas canvas) {
Matrix matrix = new Matrix();
float scaleX = getWidth() * 1f / mBitmap.getWidth();
float scaleY = getHeight() * 1f / mBitmap.getHeight();
matrix.setScale(scaleX, scaleY);
BitmapShader shader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
shader.setLocalMatrix(matrix);
mPaint.setShader(shader);
canvas.drawCircle(getWidth()/2f, getHeight()/2f, getHeight()/2, mPaint);
}
}