自定义Drawable

Posted loaderman

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义Drawable相关的知识,希望对你有一定的参考价值。

package com.loaderman.customviewdemo;

import android.graphics.*;
import android.graphics.drawable.Drawable;


public class CustomDrawable extends Drawable {
    private Paint mPaint;
    private Bitmap mBitmap;
    private BitmapShader bitmapShader;
    private RectF mBound;

    public CustomDrawable(Bitmap bitmap) {
        mBitmap = bitmap;
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
    }

    @Override
    public void draw(Canvas canvas) {
        canvas.drawRoundRect(mBound, 20, 20, mPaint);
    }


    @Override
    public void setAlpha(int alpha) {
        mPaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        mPaint.setColorFilter(cf);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;//显示模式
    }

    @Override
    public void setBounds(int left, int top, int right, int bottom) {
        super.setBounds(left, top, right, bottom);

        bitmapShader = new BitmapShader(Bitmap.createScaledBitmap(mBitmap, right - left, bottom - top, true), Shader.TileMode.CLAMP,
                Shader.TileMode.CLAMP);
        mPaint.setShader(bitmapShader);
        mBound = new RectF(left, top, right, bottom);
    }

//    @Override
//    public int getIntrinsicWidth() {
//        return mBitmap.getWidth();
//    }
//
//    @Override
//    public int getIntrinsicHeight() {
//        return mBitmap.getHeight();
//    }
}
package com.loaderman.customviewdemo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.avator);
        CustomDrawable drawable = new CustomDrawable(bitmap);
        TextView tv = (TextView) findViewById(R.id.tv);
        tv.setBackgroundDrawable(drawable);
    }
}

技术分享图片

以上是关于自定义Drawable的主要内容,如果未能解决你的问题,请参考以下文章

Android自定义View之自定义drawable

Android自定义View之自定义drawable

text 这是一个简单的代码,用于为工具栏上的后退按钮设置自定义drawable

VSCode自定义代码片段——CSS选择器

VSCode自定义代码片段6——CSS选择器

VSCode自定义代码片段(vue主模板)