您的位置:首页 > 移动开发 > Android开发

Android圆形imageview实现

2015-03-06 16:24 363 查看
现在有的应用在用户头像上使用圆形的imageview,比如百度贴吧。实现上并不困难,需要写一个类继承自ImageView,重写ondraw方法。

代码如下:

public class CircleImage extends ImageView {

	/**
	 * 3个构造函数
	 * @param context
	 */
	public CircleImage(Context context) {
		super(context);
	}

	public CircleImage(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CircleImage(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	/**
	 * 重写的ondraw方法
	 */
	@Override
	protected void onDraw(Canvas canvas) {
		Drawable drawable = getDrawable();
		if (drawable == null) {
			return;
		}

		if (getWidth() == 0 || getHeight() == 0) {
			return;
		}
		Bitmap b = ((BitmapDrawable) drawable).getBitmap();
		Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

		Bitmap roundBitmap = getCroppedBitmap(bitmap, getWidth());
		canvas.drawBitmap(roundBitmap, 0, 0, null);
	}

	/**
	 * 对bitmap进行裁剪成圆形
	 * @param bmp
	 * @param radius
	 * @return
	 */
	public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
		Bitmap sbmp;
		if (bmp.getWidth() != radius || bmp.getHeight() != radius)
			sbmp = Bitmap.createScaledBitmap(bmp, radius, radius, false);
		else
			sbmp = bmp;

		Bitmap output = Bitmap.createBitmap(sbmp.getWidth(), sbmp.getHeight(),
				Bitmap.Config.ARGB_8888);
		final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());

		Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		paint.setDither(true);
		paint.setColor(Color.parseColor("#BAB399"));

		Canvas c = new Canvas(output);
		c.drawARGB(0, 0, 0, 0);
		c.drawCircle(sbmp.getWidth() / 2 + 0.7f, sbmp.getHeight() / 2 + 0.7f,
				sbmp.getWidth() / 2 + 0.1f, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		c.drawBitmap(sbmp, rect, rect, paint);

		return output;
	}

}
然后在imageview中可以通过xml的方式进行设置

<com.example.test.CircleImage
            android:id="@+id/iv"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:adjustViewBounds="true"
            android:src="@drawable/img" />
com.example.test.CircleImage是包名+类名.

下面是实现的效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: