圆形头像之BitmapShader,Matrix实现篇

利用BitmapShader实现圆形头像的功能,可以定义边框的颜色、大小,支持padding

效果图:(为了方便看一些padding我加了黄色的背景,在onDraw()方法中第一行,去掉就可以了)


圆形头像之BitmapShader,Matrix实现篇_第1张图片

代码上该注释的地方已经注释的很清楚了

来贴一下代码:

package com.shj.view.image;


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;

import com.shj.test.R;

public class RoundImageView extends ImageView {
	private int borderColor;// 圆形头像的边框颜色
	private int borderWidth;// 圆形头像的边框宽度
	private Paint mBitmapPaint;// 绘制图像的Paint
	private Paint mBorderPaint;
	private Matrix mMatrix;// 图像矩阵,本身是一个3*3矩阵

    private int mRadius;
	private int mImgWidth;

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

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

	public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		initAttrs(context, attrs);
		mBitmapPaint = new Paint();
		mBorderPaint = new Paint();
		mMatrix = new Matrix();
		mBitmapPaint.setAntiAlias(true);
		mBorderPaint.setAntiAlias(true);

	}

	private void initAttrs(Context context, AttributeSet attrs) {
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);
		borderColor = a.getColor(R.styleable.RoundImageView_border_color, Color.parseColor("#ffffff"));
		borderWidth = a.getDimensionPixelSize(R.styleable.RoundImageView_border_width, 
                (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0, 
                        getResources().getDisplayMetrics()));
		a.recycle();
	}
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		//写好一个控件自定义View,写出一个能用的自定义View不易啊。。。
        // 虽然测量这块儿寥寥几行代码,但是还得心细啊。。
		int imgHeight = setMeasureHeight(heightMeasureSpec)-getPaddingTop() - getPaddingBottom()-borderWidth*2;
		int imgWidth = setMeasureWidth(widthMeasureSpec) - getPaddingLeft() - getPaddingRight()-borderWidth*2;
		if(imgHeight


自定义属性:


 

        
        
    


布局eg:

 
    



如果试的时候出现什么问题,烦请说一下哈,一起进步。

你可能感兴趣的:(android)