Android中绘制圆形和圆角图片

这里说到的圆角图片就是一个矩形,不过其边角不是直的线性结合,而是存在一定弧度的,例如下图的效果:


这里有一个非常关键的方法,是Paint类中的setXfermode(Xfermode xfermode)方法。关于此方法的使用和效果大家可以参见这篇博客:http://www.cnblogs.com/rayray/p/3670120.html

实际上就是用两张图片的叠加组合。在原来图片的基础上进行叠加一叠加一层自己绘制的一个圆角图片,再蒙上去。程序中我们是这样来使用的:paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));如果我们把Mode.SRC_IN换成是Mode.SCREEN,再结合上面给出的博客链接,大家就可以理解得很清晰了。

关于圆角的关键代码如下:

public static Bitmap getFilletBitmap(Bitmap bitmap) {
	    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
	    Canvas canvas = new Canvas(output);

	    final int color = 0xffEEAD0E;
	    final Paint paint = new Paint();
	    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
	    final RectF rectF = new RectF(rect);
	    final float roundPx = 100;
	  
	    paint.setAntiAlias(true);
	    canvas.drawARGB(0, 0, 0, 0);
	    paint.setColor(color);
	    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

	    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); // 这句是关键
	    canvas.drawBitmap(bitmap, rect, rect, paint);

	    return output;
	}
至于圆形的图片,是和这个是一样的。不过值得注意的是,这只是绘制圆角和圆形图片的某一种方式,还有就是可以去直接画一个圆角或圆形的View出来,这样会更加的炫。这个在以后的博客中也会提到,这里就不作过多讲解了。圆形图片的关键代码如下:

public Bitmap getRoundBitmap(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float roundPx;
		float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
		if (width <= height) {
			roundPx = width / 2;

			left = 0;
			top = 0;
			right = width;
			bottom = width;

			height = width;

			dst_left = 0;
			dst_top = 0;
			dst_right = width;
			dst_bottom = width;
		} else {
			roundPx = height / 2;

			float clip = (width - height) / 2;

			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
			width = height;

			dst_left = 0;
			dst_top = 0;
			dst_right = height;
			dst_bottom = height;
		}

		Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final Paint paint = new Paint();
		final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
		final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
		final RectF rectF = new RectF(dst);

		paint.setAntiAlias(true);// 设置画笔无锯齿

		canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas

		// 以下有两种方法画圆,drawRounRect和drawCircle
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);// 画圆角矩形,第一个参数为图形显示区域,第二个参数和第三个参数分别是水平圆角半径和垂直圆角半径。
		// canvas.drawCircle(roundPx, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://www.cnblogs.com/rayray/p/3670120.html
		canvas.drawBitmap(bitmap, src, dst, paint); // 以Mode.SRC_IN模式合并bitmap和已经draw了的Circle

		return output;
	}

工程代码下载:http://download.csdn.net/detail/u013761665/8027647

原文地址:https://www.cnblogs.com/fengju/p/6336137.html