BitmapShader实现圆形头像

BitmapShader实现圆形头像

BitmapShader是Shader的子类,通过Paint.setShader(Shader shader)进行设置

BitmapShader的构造函数需要传入3个参数

mBitmapShader = new BitmapShader(bitmap,TileMode.CLAMP,TileMode.CLAMP);

参数1:bitmap 要渲染的图片

参数2:X轴方向TileMode

参数3:Y轴方向TileMode

TileMode取值有3种:

CLAMP 拉伸

REPEAT 重复

MIRROR 镜像


废话不多直接上代码:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

/**
 * Created by asus on 2017/6/2.
 */
public class CircleImageView extends ImageView {
    //图片类型( CENTER_CROP-->水平垂直居中,进行缩放 )
    private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;
    private static final int COLORDRAWABLE_DIMESION = 2;
    private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
    //默认边框宽度
    private static final int DEFAULT_BORDER_WIDTH = 0;
    //默认边框颜色
    private static final int DEFAULT_BORDER_COLOR = Color.BLACK;

    //绘制图片范围
    private final RectF mBitmapRect = new RectF();
    //绘制边框范围
    private final RectF mBorderRect = new RectF();
    //图形变化器
    private final Matrix mShaderMatrix = new Matrix();
    //绘制图片的画笔
    private final Paint mBitmapPaint = new Paint();
    //绘制边框的画笔
    private final Paint mBorderPaint = new Paint();
    //设置默认边框大小和颜色
    private int mBorderColor = DEFAULT_BORDER_COLOR;
    private int mBorderWidth = DEFAULT_BORDER_WIDTH;

    //要绘制的图片
    private Bitmap mBitmap;
    //图片渲染器
    private BitmapShader mBitmapShader;
    //图片宽、高
    private int mBitmapWidth,mBitmapHeight;
    //图片半径
    private float mBitmapRadius;
    //图片+边框半径
    private float mBorderRadius;

    private boolean mReady;
    private boolean mSetupPending;
    private boolean mBorderOverlay;

    public CircleImageView(Context context) {
        this(context,null);
    }

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

    public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        super.setScaleType(SCALE_TYPE);
        mReady = true;
        if( mSetupPending ){
            setup();
            mSetupPending = false;
        }
    }

    private void setup() {
        if( mReady == false ){
            mSetupPending = true;
            return;
        }

        if( mBitmap == null ) return;
        //创建渲染器(参数:图片,(CLAMP表示如果图片太小就拉伸)X轴拉伸,Y轴拉伸)
        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

        //设置绘制图片的画笔
        mBitmapPaint.setAntiAlias(true);//抗锯齿
        mBitmapPaint.setShader(mBitmapShader);//设置渲染器

        //设置绘制边框的画笔
        mBorderPaint.setAntiAlias(true);//抗锯齿
        mBorderPaint.setStyle(Paint.Style.STROKE);//设置style为边框样式
        mBorderPaint.setColor(mBorderColor);//设置绘制的边框颜色
        mBorderPaint.setStrokeWidth(mBorderWidth);//设置绘制的边框大小

        mBitmapWidth = mBitmap.getWidth();
        mBitmapHeight = mBitmap.getHeight();
        //设置绘制含边框的显示范围
        mBorderRect.set(0,0,getWidth(),getHeight());
        //计算边框半径
        mBorderRadius = Math.min((mBorderRect.height()-mBorderWidth)/2,(mBorderRect.width()-mBorderWidth)/2);
        //设置绘制不包含边框的显示范围
        mBitmapRect.set(mBorderRect);
        //如果边框不是直接覆盖在图片上,缩小图片显示范围
        if( mBorderOverlay == false ){
            mBitmapRect.inset(mBorderWidth,mBorderWidth);
        }
        //计算绘制的圆形图片半径
        mBitmapRadius = Math.min(mBitmapRect.height()/2,mBitmapRect.width()/2);
        //设置渲染器的图片变化矩阵
        updateShaderMatrix();
        //手动触发onDraw进行绘制
        invalidate();
    }

    private void updateShaderMatrix() {
        float scale,dx = 0,dy = 0;
        mShaderMatrix.set(null);

        //获取最小缩放比例
        //如果x轴缩放比例大于y轴,则设置缩放比例为y轴
        if( (mBitmapWidth*mBitmapRect.height()) > (mBitmapHeight*mBitmapRect.width()) ){
            scale = mBitmapRect.height()/mBitmapHeight;
            dx = (mBitmapRect.width() - mBitmapWidth*scale)*0.5f;
        }else{
            scale = mBitmapRect.width()/mBitmapWidth;
            dy = (mBitmapRect.height() - mBitmapHeight*scale)*0.5f;
        }
        //shader的变换矩阵,我们这里主要用于放大或者缩小。
        mShaderMatrix.setScale(scale, scale);
        //平移
        mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBitmapRect.left, (int) (dy + 0.5f) + mBitmapRect.top);
        //设置变化矩阵
        mBitmapShader.setLocalMatrix(mShaderMatrix);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //没有图片直接return
        if( getDrawable() == null ) return;
        //画圆形图片(参数:圆心x坐标,圆心y坐标,圆的半径,画笔)
        canvas.drawCircle(getWidth()/2,getHeight()/2,mBitmapRadius,mBitmapPaint);
        //如果边框大于0,画圆形边框
        if( mBorderWidth > 0 ){
            canvas.drawCircle(getWidth()/2,getHeight()/2,mBorderRadius,mBorderPaint);
        }
    }

    public void setBitmap(Bitmap mBitmap) {
        this.mBitmap = mBitmap;
        setup();
    }

    public void setBorderColor(int mBorderColor) {
        this.mBorderColor = mBorderColor;
    }

    public void setBorderOverlay(boolean mBorderOverlay) {
        this.mBorderOverlay = mBorderOverlay;
    }

    public void setBorderWidth(int mBorderWidth) {
        this.mBorderWidth = mBorderWidth;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        setup();
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        mBitmap = bm;
        setup();
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        mBitmap = getBitmapFromDrawable(drawable);
        setup();
    }

    @Override
    public void setImageURI(Uri uri) {
        super.setImageURI(uri);
        mBitmap = getBitmapFromDrawable(getDrawable());
        setup();
    }

    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
        mBitmap = getBitmapFromDrawable(getDrawable());
        setup();
    }

    public Bitmap getBitmapFromDrawable(Drawable drawable){
        if( drawable == null ) return null;
        if( drawable instanceof BitmapDrawable){
            return ((BitmapDrawable) drawable).getBitmap();
        }

        try {
            Bitmap bitmap = null;
            if( drawable instanceof ColorDrawable){
                bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMESION,COLORDRAWABLE_DIMESION,BITMAP_CONFIG);
            }else{
                bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(),BITMAP_CONFIG);
            }
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0,0,canvas.getWidth(),canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
        }catch (Exception e){
            Log.e("CircleImageView", "getBitmapFromDrawable: "+e);
            return null;
        }

    }

}

代码执行的顺序是

setImageDrawable( ) 

getBitmapFromDrawable( ) 

setup( )

CircleImageView( ) 

init( )

setup( ) 

updateShaderMatrix( ) 

onSizeChanged( )

setup( )

updateShaderMatrix( ) 

onDraw( )

可以看出mReady和mSetupPending是为了保证setup中的代码必须在init后才能执行

所以可以在init中通过TypeArray获取自定义参数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值