万网制作网站,网站每年续费费用,wordpress 最新区块编辑,做英文网站要会什么在Android中#xff0c;绘制圆形和绘制图片都是很容易的事情#xff0c;但是绘制圆形图片就有点难倒人了。以前为了偷懒就直接去github上找一个开源项目#xff0c;后来才发现绘制圆形图片其实也是很简单的事。绘制圆形图片也需要两个步骤#xff1a;绘制圆形和绘制图片绘制圆形和绘制图片都是很容易的事情但是绘制圆形图片就有点难倒人了。以前为了偷懒就直接去github上找一个开源项目后来才发现绘制圆形图片其实也是很简单的事。绘制圆形图片也需要两个步骤绘制圆形和绘制图片只不过要让它们取并集得到的结果就是一张圆形图片了。直接上代码。public class CircleImageView extends View {private Paint mPaint;private Paint mTargetPaint;private Bitmap mSourceBitmap;private Bitmap mTargetBitmap;private Canvas mTargetCanvas;private int mWidth;private int mHeight;public CircleImageView(Context context) {this(context, null);}public CircleImageView(Context context, AttributeSet attrs) {this(context, attrs, 0);}public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);init();}private void init() {mPaint new Paint(Paint.ANTI_ALIAS_FLAG);mTargetPaint new Paint(Paint.ANTI_ALIAS_FLAG);mTargetPaint.setXfermode(new PorterDuffXfermode(SRC_IN));mSourceBitmap BitmapFactory.decodeResource(getResources(), R.drawable.xiaojiangshi);mTargetBitmap Bitmap.createBitmap(mSourceBitmap.getWidth(), mSourceBitmap.getHeight(), Bitmap.Config.ARGB_8888);mTargetCanvas new Canvas(mTargetBitmap);}Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh) {super.onSizeChanged(w, h, oldw, oldh);mWidth w;mHeight h;}Overrideprotected void onDraw(Canvas canvas) {// 生成圆形Bitmap过程.int radius Math.min(mWidth, mHeight) / 2;// 先绘制圆形mTargetCanvas.drawCircle(mWidth / 2, mHeight / 2, radius, mPaint);// 再绘制BitmapmTargetCanvas.drawBitmap(mSourceBitmap, 0, 0, mTargetPaint);canvas.drawBitmap(mTargetBitmap, 0, 0, null);}}效果如下代码中最关键的就是这句mTargetPaint.setXfermode(new PorterDuffXfermode(SRC_IN));SRC_IN这种模式可以让两个绘制的效果取交集后展现出来需要注意的是dst需要先绘制再绘制src拿上面例子来说就是要先绘制圆形在绘制Bitmap如果顺序颠倒了你就只能看到一个圆形了。除了SRC_IN这种模式外还有其它15种模式。有兴趣的可以自己试试看效果。在官方提供的APIDemo中可以找到相应的代码。知道这个原理之后我们就能绘制各种形状的图片了只需要绘制不同的形状代替绘制圆形这一步骤就可以了。三角形mPath.reset();mPath.moveTo(mWidth / 2, 0);mPath.lineTo(0, mHeight);mPath.lineTo(mWidth, mHeight);mPath.close();mTargetCanvas.drawPath(mPath, mPaint);扇形RectF rectF new RectF(0, 0, mWidth, mHeight);mTargetCanvas.drawArc(rectF, 210, 120, true, mPaint);