当前位置:网站首页>(原创)自定义Drawable
(原创)自定义Drawable
2022-06-27 08:02:00 【Android_xiong_st】
前言
在日常的android开发中,我们会经常用到drawable资源
比如设置icon:
imageView.setImageDrawable(R.drawable.ic_launcher);
先来看看什么是Drawable:
一般的drawable我们都是一张图
但其实我们也可以像自定义View一样
去自定义我们的Drawable
自己定义的Drawable
也可以绘制文字,形状,以及加入一些图片
做成自己需要的样子
本篇文章就通过实战来教你如何去自定义一个Drawable
效果分析
先看下效果图:
我们可以看到这个自定义的drawable有这么几个特点:
1:背景应该是一张切图,但是上面的文字是自己绘制的
2:左边的文字有描边效果
3:两个文字的位置摆放,左边的在爱心的中间,右边的文字靠在爱心的右边
下面来一步步实现这个效果
实现过程
首先我们自定义一个类来继承Drawable类:
public class MedalDrawable extends Drawable {
@Override
public void draw(@NonNull Canvas canvas) {
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
}
@Override
public int getOpacity() {
return 0;
}
}
可以看到要重写几个方法:
draw:绘制方法,这个自然不必说,和自定义View的绘制是一样的,相关的效果都是在这里绘制
setAlpha:设置Drawable的透明度,一般我们会把这个透明度传递给绘制的画笔,或者不做处理
setColorFilter:设置了一个颜色过滤器,那么在绘制出来之前,被绘制内容的每一个像素都会被颜色过滤器改变
getOpacity:获得不透明度,其值可以根据setAlpha中设置的值进行调整。比如,
alpha == 0时设置为PixelFormat.TRANSPARENT
在alpha == 255时设置为PixelFormat.OPAQUE;
在其他时候设置为PixelFormat.TRANSLUCENT
PixelFormat.OPAQUE:便是完全不透明,遮盖在他下面的所有内容
PixelFormat.TRANSPARENT:透明,完全不显示任何东西
PixelFormat.TRANSLUCENT:只有绘制的地方才覆盖底下的内容
另外还有两个方法:
getIntrinsicWidth
getIntrinsicHeight
获取内部宽度和高度,主要是为了在View使用wrap_content的时候,使用这两个方法返回的尺寸
接下来看我们的具体实现:
public MedalDrawable(int resId, String mText, Context mContext) {
this.mContext=mContext;
mBitmap = BitmapFactory.decodeResource(mContext.getResources(), resId);
this.mText = mText;
setBounds(0, 0, getIntrinsicWidth(), getIntrinsicHeight());
initPaint();//初始化勋章画笔
initThirdPaint();//初始化勋章等级画笔
}
要绘制bitmap,首先需要传进来一个资源id,然后传进来右边需要绘制的文字
左边的数字我们这里演示的时候先写死
然后就是设置下drawable的绘制区域以及初始化画笔
这边需要初始化两种画笔,分别绘制左右的文字,一个带描边效果,一个不带描边效果
最后说下描边效果怎么实现
其实原理很简单
就是绘制一个描边粗一点的文字在下面
然后把一个描边相对细一点的绘制在同样的上面
用到的就是设置画笔描边粗细的方法:
mStrokePaint.setStrokeWidth(4); //设置描边宽度
至于文字摆放的文字
是在绘制文字的时候去设置的
最后来看下源码
源码
public class MedalDrawable extends Drawable {
private Bitmap mBitmap;
private String mText;
protected Context mContext;
Paint.FontMetricsInt fontMetrics;
int marginLeft = 62;//文字距离左侧边距
int strokeMarginLeft = 0;//描边文字距离左侧边距
int textSize = 20;//文字大小
private Paint mPaint;
private Rect bounds;
private String mThirdText="21";
private Paint mThirdPaint;//勋章等级数字
private Paint mStrokePaint;//文字描边
Paint.FontMetricsInt mThridFontMetrics;
private int strokeBaseline;
public MedalDrawable(int resId, String mText, Context mContext) {
this.mContext=mContext;
mBitmap = BitmapFactory.decodeResource(mContext.getResources(), resId);
this.mText = mText;
setBounds(0, 0, getIntrinsicWidth(), getIntrinsicHeight());
initPaint();//初始化勋章画笔
initThirdPaint();//初始化勋章等级画笔
}
private void initThirdPaint() {
mThirdPaint = new Paint();
mThirdPaint.setColor(Color.parseColor("#FFFFFF"));
mThirdPaint.setFakeBoldText(true);
mThirdPaint.setAntiAlias(true);
mThirdPaint.getTextBounds(mThirdText, 0, mThirdText.length(), new Rect());
mStrokePaint = new Paint();
mStrokePaint.setColor(Color.parseColor("#bf11e6"));
mStrokePaint.setFakeBoldText(true);
mStrokePaint.setAntiAlias(true);
mStrokePaint.setStrokeWidth(4); //设置描边宽度
mStrokePaint.setStyle(Paint.Style.STROKE);
mStrokePaint.getTextBounds(mThirdText, 0, mThirdText.length(), new Rect());
if (mThirdText.length() >= 2) {
mThirdPaint.setTextSize(mContext.getResources().getDimensionPixelSize(R.dimen.text_size_6));
mStrokePaint.setTextSize(mContext.getResources().getDimensionPixelSize(R.dimen.text_size_6));
} else {
mThirdPaint.setTextSize(mContext.getResources().getDimensionPixelSize(R.dimen.text_size_9));
mStrokePaint.setTextSize(mContext.getResources().getDimensionPixelSize(R.dimen.text_size_9));
}
mThridFontMetrics = mThirdPaint.getFontMetricsInt();
}
private void initPaint() {
mPaint = new Paint();
mPaint.setColor(Color.parseColor("#FFFFFF"));
mPaint.setFakeBoldText(true);
mPaint.setAntiAlias(true);
bounds= new Rect();
mPaint.getTextBounds(mText, 0, mText.length(), bounds);
mPaint.setTextSize(textSize);
fontMetrics = mPaint.getFontMetricsInt();
}
@Override
public void draw(@NonNull Canvas canvas) {
//绘制勋章文字
int baseline = (getIntrinsicHeight() - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.drawText(mText, marginLeft, baseline, mPaint);
//绘制描边文字
strokeBaseline = (getIntrinsicHeight() - mThridFontMetrics.bottom + mThridFontMetrics.top) / 2 - mThridFontMetrics.top;
strokeMarginLeft = mContext.getResources().getDimensionPixelOffset(R.dimen.dp_5);
if (mThirdText.length() == 1) {
strokeMarginLeft = mContext.getResources().getDimensionPixelOffset(R.dimen.dp_8);
} else if (mThirdText.length() == 2) {
strokeMarginLeft = mContext.getResources().getDimensionPixelOffset(R.dimen.dp_7);
} else if (mThirdText.length() == 3) {
strokeMarginLeft = mContext.getResources().getDimensionPixelOffset(R.dimen.dp_1);
}
canvas.drawText(mThirdText, strokeMarginLeft, strokeBaseline, mStrokePaint);
canvas.drawText(mThirdText, strokeMarginLeft, strokeBaseline, mThirdPaint);
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
}
@Override
public int getOpacity() {
return PixelFormat.UNKNOWN;
}
@Override
public int getIntrinsicWidth() {
return mBitmap.getWidth();
}
@Override
public int getIntrinsicHeight() {
return mBitmap.getHeight();
}
}
边栏推荐
- 参考 | 升级 Win11 移动热点开不了或者开了连不上
- [compilation principles] review outline of compilation principles of Shandong University
- 洛谷刷题心得记录
- Windows下mysql-8下载、安装、配置教程
- Blind survey shows that female code farmers are better than male code farmers
- SQL attendance query interval: one hour
- 盲测调查显示女码农比男码农更优秀
- 大厂工作十年,年薪40万突然被裁员,公司想抛弃你,一分情面都不会留
- JS uses the while cycle to calculate how many years it will take to grow from 1000 yuan to 5000 yuan if the interest rate for many years of investment is 5%
- All tutor information on one page
猜你喜欢

2022爱分析· IT运维厂商全景报告

PayPal账户遭大规模冻结!跨境卖家如何自救?

js判断用户输入的数是否为质数(多种方法)

爬一个网页的所有导师信息

野風藥業IPO被終止:曾擬募資5.4億 實控人俞蘠曾進行P2P投資

Speech signal feature extraction process: input speech signal - framing, pre emphasis, windowing, fft- > STFT spectrum (including amplitude and phase) - square the complex number - > amplitude spectru

JS use the switch statement to output the corresponding English day of the week according to 1-7
![log4j:WARN No such property [zipPermission] in org. apache. log4j. RollingFileAppender.](/img/2c/425993cef31dd4c786f9cc5ff081ef.png)
log4j:WARN No such property [zipPermission] in org. apache. log4j. RollingFileAppender.

Testing network connectivity with the blackbox exporter

(note) Anaconda navigator flashback solution
随机推荐
【批处理DOS-CMD命令-汇总和小结】-批处理命令中的参数%0、%1、%2、%[0-9]、%0-9和批处理命令参数位置切换命令shift,dos命令中操作符%用法
R language consumption behavior statistics based on association rules and cluster analysis
JS, and output from small to large
Speech signal processing - concept (4): Fourier transform, short-time Fourier transform, wavelet transform
JS performance reward and punishment examples
File 与 MultipartFile概述
【批处理DOS-CMD命令-汇总和小结】-环境变量、路径变量、搜索文件位置相关指令——set、path、where,cmd命令的路径参数中有空格怎么办
MSSQL how to export and delete multi table data using statements
游戏资产复用:更快找到所需游戏资产的新方法
Speech signal processing - concept (II): amplitude spectrum (STFT spectrum), Mel spectrum [the deep learning of speech mainly uses amplitude spectrum and Mel spectrum] [extracted with librosa or torch
SPARQL基础入门练习
js打印99乘法表
Common operation and Principle Exploration of stream
[batch dos-cmd command - summary and summary] - how to distinguish the internal command and external command of CMD, and the difference between CMD command and run (win+r) command,
参考 | Win11 开启热点之后电脑不能上网
ACM课程学期总结
若xn>0,且x(n+1)/xn>1-1/n(n=1,2,...),证明级数∑xn发散
js例题打印1-100之间所有7的倍数的个数及总和
How to view program running time (timer) in JS
No matter how good LCD and OLED display technologies are, they cannot replace this ancient display nixie tube