美文网首页
android BitmapShader实现圆形imagev

android BitmapShader实现圆形imagev

作者: 大大大寒 | 来源:发表于2017-06-29 14:28 被阅读350次

    BitmapShader描述:
    Shader used to draw a bitmap as a texture. The bitmap can be repeated or mirrored by setting the tiling mode.
    用来将bitmap 绘制为纹理的着色器。通过设置平铺模式,位图可以重复或镜像
    BitmapShader是Shader的子类
    BitmapShader
    ComposeShader
    LinearGradient
    RadialGradient
    SweepGradient

    其他之类逐一学习使用..


    test111.png

    这是原图 我们要的效果是这样

    Screenshot_20170629113943.png

    创建一个CircleImageView继承ImageView

    主要重写
    onDraw
    onMeasure
    这两个方法

    @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            //取宽度或者高度的最小值
            int size = Math.min(getMeasuredWidth(), getMeasuredHeight());
            mRadius = size / 2;
            setMeasuredDimension(size, size);
        }
    
        private float mScale;
        private int mRadius; //圆形图片的半径
        BitmapShader mBitmapShader;
        Paint mBitmapPaint;
        @Override
        protected void onDraw(Canvas canvas) {
            //创建一个画笔
            mBitmapPaint = new Paint();
            //把Drawable转化为Bitmap 
            Bitmap bitmap = getBitmapFromDrawable(getDrawable());
            //设置一个BitmapShader
            //Shader.TileMode.CLAMP 当所画图形的尺寸大于Bitmap的尺寸的时候,会用Bitmap四边的颜色填充剩余空间
            //REPEAT  重复平铺整个绘制的区域    
            //MIRROR   镜像平铺整个绘制的区
            mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
                    Shader.TileMode.CLAMP);
            //计算缩放比例
            mScale = ((mRadius * 2.0f) / Math.min(bitmap.getHeight(), bitmap.getWidth()));
            //可以保证显示的时候图片内容照应Shader大小,否者图片显示偏移
            Matrix matrix = new Matrix();
            matrix.setScale(mScale, mScale);
            mBitmapShader.setLocalMatrix(matrix);
            //添加Shader
            mBitmapPaint.setShader(mBitmapShader);
            //画圆
            canvas.drawCircle(mRadius, mRadius, mRadius,
                    mBitmapPaint);
    
        }
    
       private Bitmap getBitmapFromDrawable(Drawable drawable) {
            if (drawable == null) {
                return null;
            }
            if (drawable instanceof BitmapDrawable) {
                return ((BitmapDrawable) drawable).getBitmap();
            }
            Bitmap bitmap;
            bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
    
        }
    

    相关文章

      网友评论

          本文标题:android BitmapShader实现圆形imagev

          本文链接:https://www.haomeiwen.com/subject/hujecxtx.html