高级UI具体自定义控件

Android 自定义圆形头像1.0

2020-04-04  本文已影响0人  啥也写不出来的安卓技术人员

两种方式   1 本地获取图片  2 通过网络获取网络图片 通过BitmapShader转为圆形图片

两种方式的实现方法相同,只是图片获取不同

一、从本地资源获取图片

//获取本地资源

Resources resources = getResources();

//拿到本地图片

Bitmap bitmap = BitmapFactory.decodeResource( resources, R.mipmap.cut );

二、从网络获取图片

//获取图片的网络路径

String commentHeadPic = resultBean.getCommentHeadPic();

//获取网络图片

try {

        new Thread(  ){

                @Override

                 public void run() {

                        super.run();

                        URL url =null;

                        try {

                            //统一资源定位符

                                url =new URL(commentHeadPic );

                                //HttpURLConnection请求网络

                                HttpURLConnection httpURLConnection = (HttpURLConnection)                                               url.openConnection();

                                //设置超时

                                httpURLConnection.setConnectTimeout(5000 );

                                httpURLConnection.connect();

                                //获取流

                                InputStream inputStream = httpURLConnection.getInputStream();

                                //转为为Bitmap格式

                                Bitmap bitmap = BitmapFactory.decodeStream( inputStream );

                                //自定义view设置bitmap

                                ivPic.setBitmap( bitmap );  

                                inputStream .clone

                }catch (Exception e) {

                        e.printStackTrace();

                }

            }

        }.start();//启动线程

      }catch (Exception e){

            String message = e.getMessage();

            Log.i(TAG,"onBindViewHolder: "+message );

}

图片获取成功后 

创建CircularView类 继承view

//全局变量

private Bitmapbitmap;

private BitmapShadershader;

private int radius;//半径

三个构造方法 无需变动

public void setBitmap(Bitmap bitmap) {

            this.bitmap = bitmap;

}

↑  这是上边通过网络获取图片 设置Bitmap的方法

测量 重写onMeasure()

//获取当前控件的最小值

int width = Math.min( getMeasuredWidth(), getMeasuredHeight() );

radius = width/2;//得到半径

绘制 重写onDraw()

if (bitmap !=null) {

      shader =new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP );

       //创建画笔

        Paint paint =new Paint();

        //抗锯齿

        paint.setAntiAlias(true );

        //设置shader

        paint.setShader(shader );

        //绘制圆形

        canvas.drawCircle(radius,radius,radius,paint);

}

仅供参考

上一篇下一篇

猜你喜欢

热点阅读