自定义控件之圆形头像

很长时间没有写博客了,先上图.

分析:这个控件,有两大部分组成.

在分析正题之前先贴出两个参数构造方法的代码和attrs的代码:

public Circle(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		//获取到TypedArray 
		TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
				R.styleable.circle, 0, 0);

		try {
			//从TypedArray 中获取到到对应xml的图片资源
			resourceId = a.getResourceId(R.styleable.circle_src,
					R.drawable.ic_launcher);
			//从TypedArray 中获取到到对应xml 圆形图片的背景颜色
			backGroung = a.getColor(R.styleable.circle_backGroung,
					Color.YELLOW);
			//从TypedArray 中获取到到对应xml 控件的左边距
			margin_left = a.getDimension(R.styleable.circle_margin_left, 0);
			//从TypedArray 中获取到到对应xml 控件的右边距
			margin_top = a.getDimension(R.styleable.circle_margin_top, 0);
			//init 方法用来创建画笔,在构造方法中一次创建画笔,避免多次创建,造成内存溢出
			init();
		} finally {
			//释放TypedArray ,否则会造成内存泄漏
			a.recycle();
		}
	}
在res下的values 目录 创建文件名字为attrs文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 获取TypedArray的名字 (自定义)-->
     <declare-styleable name="circle"> 
       <!-- name 根据内容合理起名字  dimension 尺寸(固定属性)单位是dp-->
       <attr name="margin_top" format="dimension"/>  
       <attr name="margin_left" format="dimension"/> 
       <!-- name 根据内容合理起名字  reference 资源(固定属性)单位是 int-->
       <attr name="src" format="reference"/>
       <!-- name 根据内容合理起名字  color 颜色(固定属性)单位是 int-->
       <attr name="backGroung" format="color"/>  
   </declare-styleable>  
</resources>
关于具体的属性:可参考: 点击打开链接

1:圆形部分:

首先:创建一个画笔,用来画背景;

paint1 = new Paint();
        //抗锯齿的两种方式  参考:http://blog.youkuaiyun.com/yixinyouni1314/article/details/7774164
        paint1.setAntiAlias(true);
        paint1.setFilterBitmap(true);
        //设定背景颜色
        paint1.setColor(backGroung);
其次:在画板上画出圆形

canvas.drawCircle(dpToPx((float) 50+margin_left), dpToPx((float) 50+margin_top),
				dpToPx((float) 50), paint1);

工具类:dpToPx稍后贴出源码:作用dp转换成px

2:图片处理部分:

图片不需要用到画笔,所以不必创建.

//将从xml拿到的图片资源id,转换成bitMap
		Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
				resourceId);
		//该方法用来,处理bitmap,让图片的宽高拉伸或者压缩到 圆形图片的宽高,代码稍后贴出
		Bitmap newBitmap = scaleBitmap(bitmap, dpToPx((float) 100),
				dpToPx((float) 100));
		//根据位置(左边位置,上边位置),画出该图片 ,不需要画笔所以为null
		canvas.drawBitmap(newBitmap, dpToPx((float) 0+margin_left), dpToPx((float) 0+margin_top), null);
		//合并图层
		canvas.restore();
图片不需要用到画笔,所以不必创建.

3.测量部分代码

关于测量模式,有不懂的,可以参考这篇文章:点击打开链接

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
		int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
		int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
		int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

		if (widthSpecMode == MeasureSpec.EXACTLY
				&& heightSpecMode == MeasureSpec.EXACTLY) {// 如果是精准测量模式,默认测量模式
			setMeasuredDimension(widthSpecSize, heightSpecSize);// 那么就让其等于测量尺寸
		} else {
			if (widthSpecMode == MeasureSpec.AT_MOST
					&& heightSpecMode == MeasureSpec.AT_MOST) {// 如果是最大测量尺寸,那么就取二者中最小的
				int width = Math.round(dpToPx((float) 100+margin_left));
				int height = Math.round(dpToPx((float) 100+margin_top));
				setMeasuredDimension(width, height);
			}
		}
	}

4.工具类代码

有关工具类,推荐一篇不错的博文:张鸿翔的十大常用工具类点击打开链接

dp转换成px

    public static int dp2px(Context context, float dpVal)  
	    {  
	        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,  
	                dpVal, context.getResources().getDisplayMetrics());  
	    } 
dp转换成px,2次封装

public Float dpToPx(Float f) {
		return (float) DensityUtils.dp2px(context, f);
	}

按照比例处理bitmap

/**
	 * 把图片压缩成宽高等于圆的半径
	 * 
	 */
	private static Bitmap scaleBitmap(Bitmap bitmap, Float width, Float height) {
		Matrix matrix = new Matrix();
		int scaleWidth = bitmap.getWidth();
		int scaleHeight = bitmap.getHeight();
		//参数大于1放大,小于1缩小
		matrix.postScale( width/scaleWidth, height/scaleHeight); // 长和宽放大缩小的比例
		//按照比例生成新的bitmap
		Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, scaleWidth,
				scaleHeight, matrix, true);
		return resizeBmp;
	}

5.布局文件的使用

下面到了激动人心的使用环节,直接上代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:zdy="http://schemas.android.com/apk/res/com.example.demo"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.zdykj.circleview.Circle
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        zdy:backGroung="#22b14c"
        zdy:margin_left="10dp"
        zdy:margin_top="10dp"
        zdy:src="@drawable/ic_launcher" />

</LinearLayout>

解释说明 :重要,重要,重要  重要的事情说三遍
   xmlns:zdy="http://schemas.android.com/apk/res/com.example.demo"
<span style="color:#CC33CC;">其中后面的包名一定是,工程的包名,否则你会发现你的xml自定义控件部分,一直报错
前面的zdy(命名空间):可以随便起名字

使用的时候注意:命名空间:属性名称="对应的内容" 即可
</span>

缺点是:不能用 layout_marginLeft 或者 layout_marginTop  因为我发现画图片的坐标是以父控件的左上角为参考点,圆形部分则不是,会造成图片和背景偏移

有大神欢迎提出改正.

补充:我把空间打成了jar包

jar包地址链接:点击打开链接

使用说明:

1.考入attrs文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <declare-styleable name="circle"> 
       <attr name="margin_top" format="dimension"/>  
       <attr name="margin_left" format="dimension"/> 
       <attr name="src" format="reference"/>
       <attr name="backGroung" format="color"/>  
   </declare-styleable>  
</resources>

2.在布局中使用

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:zdy="http://schemas.android.com/apk/res/com.example.demo"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.zdykj.circleview.Circle
        android:layout_marginLeft=""
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        zdy:backGroung="#22b14c"
        zdy:margin_left="10dp"
        zdy:margin_top="10dp"
        zdy:src="@drawable/ic_launcher" />

</LinearLayout>


效果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值