Android 完美實現圖片圓角和圓形(對實現進行分析)


轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/24555655

本來想在網上找個圓角的樣例看一看,不盡人意啊,基本都是官方的Demo的那張原理圖。稍后會貼出。

於是自己自己定義了個View,實現圖片的圓角以及圓形效果。效果圖:


第一個是原圖,第二個是圓形效果。第三第四設置了不同的圓角大小。

准備改變一個博客的風格,首先給大家講一下原理,讓大家明確了,然后再貼代碼,不然能夠直接看那么長的代碼也比較痛苦。核心代碼事實上就那么幾行:

核心代碼分析:

/**
	 * 依據原圖和變長繪制圓形圖片
	 * 
	 * @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,就實現了圓形圖片效果。

圓角,事實上就是先繪制圓角矩形,是不是非常easy,以后別人再說實現圓角。你就把這一行代碼給他即可了。

從Android的演示樣例中,給大家證明一下:

以下有一張PorterDuff.Mode的16中效果圖,咱們的僅僅是其一:


源代碼咱們僅僅關心誰先誰后繪制的:

  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、自己定義屬性:

<?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、構造中獲取自己定義的屬性:
	/**
	 * 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:
				mRadius= a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10f,
						getResources().getDisplayMetrics()));// 默覺得10DP
				break;
			}
		}
		a.recycle();
	}

3、onMeasure中獲取控件寬高:

/**
	 * 計算控件的高度和寬度
	 */
	@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);
			} else

				mWidth = desireByImg;
		}

		/***
		 * 設置高度
		 */

		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);
			} else
				mHeight = desire;
		}

		setMeasuredDimension(mWidth, mHeight);

	}



4、依據Type繪制:

/**
	 * 繪制
	 */
	@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, mRadius, mRadius, paint);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		canvas.drawBitmap(source, 0, 0, paint);
		return target;
	}

好了,我就不解析代碼了,自己定義View這是第五篇了。。,。寫得好惡心,,,。


各位贊一個或者留個言。算是對我的支持~


源代碼點擊下載



=========================================簡單修復了一下,在ScrollView以及AdapterView中的headview的顯示異常的bug============

修復后代碼下載:

源代碼點擊下載


相關博文,同一時候也推薦使用:

Android Xfermode 實戰 實現圓形、圓角圖片

Android BitmapShader 實戰 實現圓形、圓角圖片



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM