Android 完美实现图片圆角和圆形(对实现进行分析)

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/24555655

本来想在网上找个圆角的例子看一看,不尽人意啊,基本都是官方的Demo的那张原理图,稍后会贴出。于是自己自定义了个View,实现图片的圆角以及圆形效果。效果图:


第一个是原图,第二个是圆形效果,第三第四设置了不同的圆角大小。

准备改变一个博客的风格,首先给大家讲一下原理,让大家明白了,然后再贴代码,不然可以直接看那么长的代码也比较痛苦,核心代码其实就那么几行:

核心代码分析:

  1. /**
  2.      * 根据原图和变长绘制圆形图片
  3.      *
  4.      * @param source
  5.      * @param min
  6.      * @return
  7.      */ 
  8.     private Bitmap createCircleImage(Bitmap source, int min) 
  9.     { 
  10.         final Paint paint = new Paint(); 
  11.         paint.setAntiAlias(true); 
  12.         Bitmap target = Bitmap.createBitmap(min, min, Config.ARGB_8888); 
  13.         /**
  14.          * 产生一个同样大小的画布
  15.          */ 
  16.         Canvas canvas = new Canvas(target); 
  17.         /**
  18.          * 首先绘制圆形
  19.          */ 
  20.         canvas.drawCircle(min / 2, min / 2, min / 2, paint); 
  21.         /**
  22.          * 使用SRC_IN
  23.          */ 
  24.         paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); 
  25.         /**
  26.          * 绘制图片
  27.          */ 
  28.         canvas.drawBitmap(source, 0, 0, paint); 
  29.         return target; 
  30.     } 
/**
	 * 根据原图和变长绘制圆形图片
	 * 
	 * @param source
	 * @param min
	 * @return
	 */
	private Bitmap createCircleImage(Bitmap source, int min)
	{
		final Paint paint = new Paint();
		paint.setAntiAlias(true);
		Bitmap target = Bitmap.createBitmap(min, min, Config.ARGB_8888);
		/**
		 * 产生一个同样大小的画布
		 */
		Canvas canvas = new Canvas(target);
		/**
		 * 首先绘制圆形
		 */
		canvas.drawCircle(min / 2, min / 2, min / 2, paint);
		/**
		 * 使用SRC_IN
		 */
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		/**
		 * 绘制图片
		 */
		canvas.drawBitmap(source, 0, 0, paint);
		return target;
	}

其实主要靠:paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));这行代码,为什么呢,我给大家解释下,SRC_IN这种模式,两个绘制的效果叠加后取交集展现后图,怎么说呢,咱们第一个绘制的是个圆形,第二个绘制的是个Bitmap,于是交集为圆形,展现的是BItmap,就实现了圆形图片效果。圆角,其实就是先绘制圆角矩形,是不是很简单,以后别人再说实现圆角,你就把这一行代码给他就行了。

从Android的示例中,给大家证明一下:

下面有一张PorterDuff.Mode的16中效果图,咱们的只是其一:


源码咱们只关心谁先谁后绘制的:

  1. canvas.translate(x, y); 
  2.               canvas.drawBitmap(mDstB, 0, 0, paint); 
  3.               paint.setXfermode(sModes[i]); 
  4.               canvas.drawBitmap(mSrcB, 0, 0, paint); 
  5.               paint.setXfermode(null); 
  6.               canvas.restoreToCount(sc); 
  canvas.translate(x, y);
                canvas.drawBitmap(mDstB, 0, 0, paint);
                paint.setXfermode(sModes[i]);
                canvas.drawBitmap(mSrcB, 0, 0, paint);
                paint.setXfermode(null);
                canvas.restoreToCount(sc);
可以看出先绘制的Dst,再绘制的Src,最后的展示是SrcIn那个图:显示的区域是二者交集,展示的是Src(后者)。和咱们前面结论一致。效果16种,大家可以自由组合展示不同的效果。


好了,原理和核心代码解释完成。下面开始写自定义View。

1、自定义属性:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources> 
  3.  
  4.     <attr name="borderRadius" format="dimension" /> 
  5.     <attr name="type"> 
  6.         <enum name="circle" value="0" /> 
  7.         <enum name="round" value="1" /> 
  8.     </attr> 
  9.     <attr name="src" format="reference"></attr> 
  10.  
  11.     <declare-styleable name="CustomImageView"> 
  12.         <attr name="borderRadius" /> 
  13.         <attr name="type" /> 
  14.         <attr name="src" /> 
  15.     </declare-styleable> 
  16.  
  17. </resources> 
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <attr name="borderRadius" format="dimension" />
    <attr name="type">
        <enum name="circle" value="0" />
        <enum name="round" value="1" />
    </attr>
    <attr name="src" format="reference"></attr>

    <declare-styleable name="CustomImageView">
        <attr name="borderRadius" />
        <attr name="type" />
        <attr name="src" />
    </declare-styleable>

</resources>

2、构造中获取自定义的属性:
  1. /**
  2. * TYPE_CIRCLE / TYPE_ROUND
  3. */ 
  4. private int type; 
  5. private static final int TYPE_CIRCLE = 0
  6. private static final int TYPE_ROUND = 1
  7.  
  8. /**
  9. * 图片
  10. */ 
  11. private Bitmap mSrc; 
  12.  
  13. /**
  14. * 圆角的大小
  15. */ 
  16. private int mRadius; 
  17.  
  18. /**
  19. * 控件的宽度
  20. */ 
  21. private int mWidth; 
  22. /**
  23. * 控件的高度
  24. */ 
  25. private int mHeight; 
  26.  
  27. public CustomImageView(Context context, AttributeSet attrs) 
  28.     this(context, attrs, 0); 
  29.  
  30. public CustomImageView(Context context) 
  31.     this(context, null); 
  32.  
  33. /**
  34. * 初始化一些自定义的参数
  35. *
  36. * @param context
  37. * @param attrs
  38. * @param defStyle
  39. */ 
  40. public CustomImageView(Context context, AttributeSet attrs, int defStyle) 
  41.     super(context, attrs, defStyle); 
  42.  
  43.     TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomImageView, defStyle, 0); 
  44.  
  45.     int n = a.getIndexCount(); 
  46.     for (int i = 0; i < n; i++) 
  47.     { 
  48.         int attr = a.getIndex(i); 
  49.         switch (attr) 
  50.         { 
  51.         case R.styleable.CustomImageView_src: 
  52.             mSrc = BitmapFactory.decodeResource(getResources(), a.getResourceId(attr, 0)); 
  53.             break
  54.         case R.styleable.CustomImageView_type: 
  55.             type = a.getInt(attr, 0);// 默认为Circle 
  56.             break
  57.         case R.styleable.CustomImageView_borderRadius: 
  58.             type = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10f, 
  59.                     getResources().getDisplayMetrics()));// 默认为10DP 
  60.             break
  61.         } 
  62.     } 
  63.     a.recycle(); 
	/**
	 * TYPE_CIRCLE / TYPE_ROUND
	 */
	private int type;
	private static final int TYPE_CIRCLE = 0;
	private static final int TYPE_ROUND = 1;

	/**
	 * 图片
	 */
	private Bitmap mSrc;

	/**
	 * 圆角的大小
	 */
	private int mRadius;

	/**
	 * 控件的宽度
	 */
	private int mWidth;
	/**
	 * 控件的高度
	 */
	private int mHeight;

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

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

	/**
	 * 初始化一些自定义的参数
	 * 
	 * @param context
	 * @param attrs
	 * @param defStyle
	 */
	public CustomImageView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);

		TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomImageView, defStyle, 0);

		int n = a.getIndexCount();
		for (int i = 0; i < n; i++)
		{
			int attr = a.getIndex(i);
			switch (attr)
			{
			case R.styleable.CustomImageView_src:
				mSrc = BitmapFactory.decodeResource(getResources(), a.getResourceId(attr, 0));
				break;
			case R.styleable.CustomImageView_type:
				type = a.getInt(attr, 0);// 默认为Circle
				break;
			case R.styleable.CustomImageView_borderRadius:
				type = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10f,
						getResources().getDisplayMetrics()));// 默认为10DP
				break;
			}
		}
		a.recycle();
	}

3、onMeasure中获取控件宽高:

  1. /**
  2.      * 计算控件的高度和宽度
  3.      */ 
  4.     @Override 
  5.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
  6.     { 
  7.         // super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
  8.  
  9.         /**
  10.          * 设置宽度
  11.          */ 
  12.         int specMode = MeasureSpec.getMode(widthMeasureSpec); 
  13.         int specSize = MeasureSpec.getSize(widthMeasureSpec); 
  14.  
  15.         if (specMode == MeasureSpec.EXACTLY)// match_parent , accurate 
  16.         { 
  17.             mWidth = specSize; 
  18.         } else 
  19.         { 
  20.             // 由图片决定的宽 
  21.             int desireByImg = getPaddingLeft() + getPaddingRight() + mSrc.getWidth(); 
  22.             if (specMode == MeasureSpec.AT_MOST)// wrap_content 
  23.             { 
  24.                 mWidth = Math.min(desireByImg, specSize); 
  25.             } 
  26.         } 
  27.  
  28.         /***
  29.          * 设置高度
  30.          */ 
  31.  
  32.         specMode = MeasureSpec.getMode(heightMeasureSpec); 
  33.         specSize = MeasureSpec.getSize(heightMeasureSpec); 
  34.         if (specMode == MeasureSpec.EXACTLY)// match_parent , accurate 
  35.         { 
  36.             mHeight = specSize; 
  37.         } else 
  38.         { 
  39.             int desire = getPaddingTop() + getPaddingBottom() + mSrc.getHeight(); 
  40.             if (specMode == MeasureSpec.AT_MOST)// wrap_content 
  41.             { 
  42.                 mHeight = Math.min(desire, specSize); 
  43.             } 
  44.         } 
  45.         setMeasuredDimension(mWidth, mHeight); 
  46.  
  47.     } 
/**
	 * 计算控件的高度和宽度
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		// super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		/**
		 * 设置宽度
		 */
		int specMode = MeasureSpec.getMode(widthMeasureSpec);
		int specSize = MeasureSpec.getSize(widthMeasureSpec);

		if (specMode == MeasureSpec.EXACTLY)// match_parent , accurate
		{
			mWidth = specSize;
		} else
		{
			// 由图片决定的宽
			int desireByImg = getPaddingLeft() + getPaddingRight() + mSrc.getWidth();
			if (specMode == MeasureSpec.AT_MOST)// wrap_content
			{
				mWidth = Math.min(desireByImg, specSize);
			}
		}

		/***
		 * 设置高度
		 */

		specMode = MeasureSpec.getMode(heightMeasureSpec);
		specSize = MeasureSpec.getSize(heightMeasureSpec);
		if (specMode == MeasureSpec.EXACTLY)// match_parent , accurate
		{
			mHeight = specSize;
		} else
		{
			int desire = getPaddingTop() + getPaddingBottom() + mSrc.getHeight();
			if (specMode == MeasureSpec.AT_MOST)// wrap_content
			{
				mHeight = Math.min(desire, specSize);
			}
		}
		setMeasuredDimension(mWidth, mHeight);

	}

4、根据Type绘制:

  1. /**
  2.      * 绘制
  3.      */ 
  4.     @Override 
  5.     protected void onDraw(Canvas canvas) 
  6.     { 
  7.  
  8.         switch (type) 
  9.         { 
  10.         // 如果是TYPE_CIRCLE绘制圆形 
  11.         case TYPE_CIRCLE: 
  12.  
  13.             int min = Math.min(mWidth, mHeight); 
  14.             /**
  15.              * 长度如果不一致,按小的值进行压缩
  16.              */ 
  17.             mSrc = Bitmap.createScaledBitmap(mSrc, min, min, false); 
  18.  
  19.             canvas.drawBitmap(createCircleImage(mSrc, min), 0, 0, null); 
  20.             break
  21.         case TYPE_ROUND: 
  22.             canvas.drawBitmap(createRoundConerImage(mSrc), 0, 0, null); 
  23.             break
  24.  
  25.         } 
  26.  
  27.     } 
  28.  
  29.     /**
  30.      * 根据原图和变长绘制圆形图片
  31.      *
  32.      * @param source
  33.      * @param min
  34.      * @return
  35.      */ 
  36.     private Bitmap createCircleImage(Bitmap source, int min) 
  37.     { 
  38.         final Paint paint = new Paint(); 
  39.         paint.setAntiAlias(true); 
  40.         Bitmap target = Bitmap.createBitmap(min, min, Config.ARGB_8888); 
  41.         /**
  42.          * 产生一个同样大小的画布
  43.          */ 
  44.         Canvas canvas = new Canvas(target); 
  45.         /**
  46.          * 首先绘制圆形
  47.          */ 
  48.         canvas.drawCircle(min / 2, min / 2, min / 2, paint); 
  49.         /**
  50.          * 使用SRC_IN,参考上面的说明
  51.          */ 
  52.         paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); 
  53.         /**
  54.          * 绘制图片
  55.          */ 
  56.         canvas.drawBitmap(source, 0, 0, paint); 
  57.         return target; 
  58.     } 
  59.  
  60.     /**
  61.      * 根据原图添加圆角
  62.      *
  63.      * @param source
  64.      * @return
  65.      */ 
  66.     private Bitmap createRoundConerImage(Bitmap source) 
  67.     { 
  68.         final Paint paint = new Paint(); 
  69.         paint.setAntiAlias(true); 
  70.         Bitmap target = Bitmap.createBitmap(mWidth, mHeight, Config.ARGB_8888); 
  71.         Canvas canvas = new Canvas(target); 
  72.         RectF rect = new RectF(0, 0, source.getWidth(), source.getHeight()); 
  73.         canvas.drawRoundRect(rect, 50f, 50f, paint); 
  74.         paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); 
  75.         canvas.drawBitmap(source, 0, 0, paint); 
  76.         return target; 
  77.     } 
/**
	 * 绘制
	 */
	@Override
	protected void onDraw(Canvas canvas)
	{

		switch (type)
		{
		// 如果是TYPE_CIRCLE绘制圆形
		case TYPE_CIRCLE:

			int min = Math.min(mWidth, mHeight);
			/**
			 * 长度如果不一致,按小的值进行压缩
			 */
			mSrc = Bitmap.createScaledBitmap(mSrc, min, min, false);

			canvas.drawBitmap(createCircleImage(mSrc, min), 0, 0, null);
			break;
		case TYPE_ROUND:
			canvas.drawBitmap(createRoundConerImage(mSrc), 0, 0, null);
			break;

		}

	}

	/**
	 * 根据原图和变长绘制圆形图片
	 * 
	 * @param source
	 * @param min
	 * @return
	 */
	private Bitmap createCircleImage(Bitmap source, int min)
	{
		final Paint paint = new Paint();
		paint.setAntiAlias(true);
		Bitmap target = Bitmap.createBitmap(min, min, Config.ARGB_8888);
		/**
		 * 产生一个同样大小的画布
		 */
		Canvas canvas = new Canvas(target);
		/**
		 * 首先绘制圆形
		 */
		canvas.drawCircle(min / 2, min / 2, min / 2, paint);
		/**
		 * 使用SRC_IN,参考上面的说明
		 */
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		/**
		 * 绘制图片
		 */
		canvas.drawBitmap(source, 0, 0, paint);
		return target;
	}

	/**
	 * 根据原图添加圆角
	 * 
	 * @param source
	 * @return
	 */
	private Bitmap createRoundConerImage(Bitmap source)
	{
		final Paint paint = new Paint();
		paint.setAntiAlias(true);
		Bitmap target = Bitmap.createBitmap(mWidth, mHeight, Config.ARGB_8888);
		Canvas canvas = new Canvas(target);
		RectF rect = new RectF(0, 0, source.getWidth(), source.getHeight());
		canvas.drawRoundRect(rect, 50f, 50f, paint);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		canvas.drawBitmap(source, 0, 0, paint);
		return target;
	}

好了,我就不解析代码了,自定义View这是第五篇了,,,,写得好恶心,,,,


各位赞一个或者留个言,算是对我的支持~


源码点击下载

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值