BitmapShader绘制圆形图片

来源:互联网 发布:淘宝如何贷款 编辑:程序博客网 时间:2024/05/16 05:12

今天我们使用BitmapShader
自定义View,继承ImageView

/** * Created by softpo on 2016/10/29. */public class CircleImageView extends ImageView {    private Bitmap mBitmap;    private int mWidth,mHeight;    private BitmapShader mBitmapShader;    private ShapeDrawable mShapeDrawable;    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);        //得到图像        mBitmap = ((BitmapDrawable) getDrawable()).getBitmap();        mWidth = mBitmap.getWidth();        mHeight = mBitmap.getHeight();        //构造渲染器BitmapShader        /*         CLAMP  :如果渲染器超出原始边界范围,会复制范围内边缘染色。         REPEAT :横向和纵向的重复渲染器图片,平铺。         MIRROR :横向和纵向的重复渲染器图片,这个和REPEAT 重复方式不一样,它是以镜像方式平铺。         */        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.MIRROR,Shader.TileMode.REPEAT);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);        //精确赋值        /**         * EXACTLY:当我们设置width或height为match_parent或者固定值时,容器在布局时调用子 view的measure方法传入的模式是EXACTLY,         * 因为子view会占据剩余容器的空间,所以它大小是确定的;         *         * AT_MOST:而当设置为 wrap_content时,容器传进去的是AT_MOST,         * 表示子view的大小最多是多少,这样子view会根据这个上限来设置自己的尺寸;         *          * UNSPECIFIED:是未指定尺寸,这种情况不多,一般都是父控件是AdapterView,通过measure方法传入的模式         */        if(modeWidth==MeasureSpec.EXACTLY&&modeHeight==MeasureSpec.EXACTLY){            mWidth = MeasureSpec.getSize(widthMeasureSpec);            mHeight = MeasureSpec.getSize(heightMeasureSpec);        }        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }    @Override    protected void onDraw(Canvas canvas) {//        super.onDraw(canvas);        //将图片裁剪为椭圆形        //构建ShapeDrawable对象并定义形状为椭圆        mShapeDrawable = new ShapeDrawable(new OvalShape());        //得到画笔并设置渲染器        mShapeDrawable.getPaint().setShader(mBitmapShader);        //设置显示区域        mShapeDrawable.setBounds(20, 20,mWidth,mHeight);        //绘制shapeDrawable        mShapeDrawable.draw(canvas);    }}

布局中使用:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.softpo.customviewdemo.MainActivity">    <com.softpo.customviewdemo.widget.CircleImageView        android:src="@mipmap/p7"        android:layout_width="300dp"        android:layout_height="300dp"/></RelativeLayout>

效果图:
一:MIRROR :横向和纵向的重复渲染器图片,这个和REPEAT 重复方式不一样,它是以镜像方式平铺

二:REPEAT :横向和纵向的重复渲染器图片,平铺
这里写图片描述
三:CLAMP :如果渲染器超出原始边界范围,会复制范围内边缘染色。
这里写图片描述

1 0