android自定义圆形drawable

RT:既然是自定义drawable肯定是继承自drawable

由四个必须要实现的方法,

1.draw(@NonNullCanvas canvas);

绘制,通常是用画笔在canvas上面进行操作,也可以选定一块区域,让他只能在区域内进行绘制


2.setAlpha(@IntRange(from =0, to =255)intalpha);

设置透明度,通常是通过画笔来实现,我们直接调用

paint.setAlpha(alpha);
 

3.setColorFilter(@NullableColorFilter colorFilter);

设置颜色过滤器,也是通过画笔来实现的,这里也是直接调用

paint.setColorFilter(colorFilter);

4.getOpacity();

返回这个可拉伸图的透明性,这里我们直接返回的是系统的

PixelFormat.TRANSLUCENT
系统选择一种支持半透明的格式,这是对其注释的翻译

原文:

System chooses a format that supports translucency (many alpha bits)


另外还有两个方法:

getIntrinsicHeight();

getIntrinsicWidth();
返回drawable固定的宽高。因为我们这里是已自定义圆形drawable,
所以直接返回bitmap对应的最小长宽就可以了
 
 
BitmapShader
位图着色器,这个没用过,我也不知道是干嘛的,
猜测就是作用和bitmap差不多,但是进去后发现是调用的jni
也不知道里面究竟是做了什么,但是返回了Shader,直接把
Shader设置给了画笔,也就是说,最终还是由画笔来完成的绘制
/**
 * Draw the specified circle using the specified paint. If radius is <= 0,
 * then nothing will be drawn. The circle will be filled or framed based
 * on the Style in the paint.
 *
 * @param cx     The x-coordinate of the center of the cirle to be drawn   center-X  坐标中心X
 * @param cy     The y-coordinate of the center of the cirle to be drawn  center-Y 坐标中心Y
 * @param radius The radius of the cirle to be drawn    半径
 * @param paint  The paint used to draw the circle	画笔
 */

drawCircle(float cx, float cy, float radius, @NonNull Paint paint);
好了,废话说了这么多,下面就开始上代码,不要问我代码是谁,我也不知道。。。

/**
 * Created by 空 on 2017/7/30.
 * 圆形的drawable
 */

public class CustomDrawable extends Drawable {

    Paint paint = new Paint();
    Bitmap bitmap;
    private final BitmapShader bitmapShader;
    private final int min;

    public CustomDrawable(Bitmap bitmap) {
        this.bitmap = bitmap;
        paint.setAntiAlias(true);

        bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        paint.setShader(bitmapShader);

        min = Math.min(bitmap.getWidth(), bitmap.getHeight());

    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        int width = min / 2;
        canvas.drawCircle(width, width, width, paint);
    }

    @Override
    public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {
        paint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(@Nullable ColorFilter colorFilter) {
        paint.setColorFilter(colorFilter);
    }

    //屏幕默认的一种半透明的格式  不透明度
    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    @Override
    public int getIntrinsicHeight() {
        return min;
    }

    @Override
    public int getIntrinsicWidth() {
        return min;
    }

}

代码就这么多了,博主水平有限,若有错误,欢迎指正



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值