Android圆形头像自己动手
发表时间:2020-10-19
发布人:葵宇科技
浏览次数:44
圆形头像DIY
如今大年夜部分app应用的都是圆形头像,网上开源的也很多,然则有没有推敲过DIY圆形头像呢?下面就本身实现一个,先看下demo展示
[img]http://img.blog.csdn.net/20150105120136311?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY21sX2Jsb2c=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
第一步:道理解释(图片很丑,道理很真)
1、画外框圆形,须要应用自定义的色彩画一个圆形,比图片的半径长5dp
[img]http://img.blog.csdn.net/20150105120850921?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY21sX2Jsb2c=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
2、自定义圆形画好了后,将我们须要转换成圆形头像的图片画到膳绫擎,大年夜中心开端覆盖,获得如下图片
[img]http://img.blog.csdn.net/20150105120934733?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY21sX2Jsb2c=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
3、中心朝长进步图片,半径设置为:r=min(width,height),圆心设为:cx=width/2,cy=height/2,如许可以大年夜中心开端朝长进步圆形图片
第二步、代码实现
1、起首持续ImageView
2、重写onDraw(Canvas canvas)办法
3、设置图片缩放类型setScaleType(ScaleType.CENTER_CROP); 中心朝长进步
具体代码如下:
@Override protected void onDraw(Canvas canvas) { // super.onDraw(canvas); setScaleType(ScaleType.CENTER_CROP); Drawable drawable = getDrawable(); if (null == drawable) { return; } // 将drawable转换成bitmap==>网上找的 Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas srcCanvas = new Canvas(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(srcCanvas); float cx = getWidth() / 2; float cy = getHeight() / 2; float radius = Math.min(getWidth(), getHeight()) / 2; Paint borderPaint = new Paint(); borderPaint.setAntiAlias(true); borderPaint.setColor(Color.GREEN); canvas.drawCircle(cx, cy, radius, borderPaint); // 画图 BitmapShader shader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP); Paint paint = new Paint(); paint.setShader(shader); paint.setAntiAlias(true); canvas.drawCircle(cx, cy, radius - 5, paint); }
代码只是简单的demo,当然可以定制成通用的CircleImageView,须要根据本身的需求DIY!!