自定义圆角View
最近有个产品需求,需要用圆角图片展示内容。在网上搜了一下,有两个方案:shader和xfermode。最终考虑到内存占用问题,我们选择了shader。
下面先分别说下shader和xfermode的基本用法,然后给出对应的圆角实现代码。
shader
shader被翻译成着色器,顾名思义:画笔的颜色。在android中,shader是有很多实现子类的,这里不多介绍,本文中使用到是BitmapShader:将一个位图转化成画笔的色彩。下面先给个画出图片的demo,来感受一下shader的效果。
public class RoundImageView2 extends android.support.v7.widget.AppCompatImageView { private float[] roundArray = { 0.f,0.f,0.f,0.f,0.f,0.f,0.f,0.f}; private Path mPath; private Paint mPaint; private Bitmap mBitmap; private float moveX = 0.f; private float moveY = 0.f; public RoundImageView2(Context context) { super(context); } public RoundImageView2(Context context, AttributeSet attrs) { super(context, attrs); init(context,attrs); } private void init(Context context,AttributeSet attrs){ mPath = new Path(); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(30f); } @Override protected void onDraw(Canvas canvas) { mBitmap = getBitMap(); BitmapShader bitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mPaint.setShader(bitmapShader); canvas.drawPath(mPath,mPaint); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: // mPath.reset(); mPath.moveTo(event.getX(),event.getY()); break; case MotionEvent.ACTION_MOVE: moveX = event.getX(); moveY = event.getY(); mPath.lineTo(moveX,moveY); invalidate(); break; case MotionEvent.ACTION_UP: break; } return true; } private Bitmap getBitMap(){ Drawable drawable = getDrawable(); if(drawable == null){ return null; } Bitmap bitmap; if(drawable instanceof BitmapDrawable){ BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; bitmap = bitmapDrawable.getBitmap(); }else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); drawable.draw(new Canvas(bitmap)); } return bitmap; }
上面的demo展示了使用shader实现涂鸦的效果。下面看圆角怎么实现:1.给创建一个图片的BitmapShader。2.然后画出圆角的形状。在canvas中,圆角可以使用Path的addRoundRect()定出。再通过canvas.drawPath就可以完成形状的绘制。形状有了,只需要在画形状的时候添加着色器:public class RoundImageView extends android.support.v7.widget.AppCompatImageView {