当前位置:网站首页>(original) custom drawable
(original) custom drawable
2022-06-27 08:18:00 【Android_ xiong_ st】
Preface
In everyday android In development , We will use it often drawable resources
Setting up icon:
imageView.setImageDrawable(R.drawable.ic_launcher);
Let's see what is Drawable:
General drawable We are all one picture
But in fact, we can also customize View equally
To customize our Drawable
Self defined Drawable
You can also draw text , shape , And add some pictures
Be what you need
This article will teach you how to customize a Drawable
Effect analysis
Let's take a look at the renderings first :
We can see this customized drawable There are several characteristics :
1: The background should be a cut , But the above text was drawn by myself
2: The text on the left has a stroke effect
3: The position of the two words , The one on the left is in the middle of love , The words on the right lean against the right of love
Let's take this effect step by step
Implementation process
First, we customize a class to inherit Drawable class :
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;
}
}
You can see several methods to rewrite :
draw: Drawing method , Naturally, there is no need to say , And customization View The drawing of is the same , The relevant effects are drawn here
setAlpha: Set up Drawable Transparency , Generally, we will pass this transparency to the paintbrush , Or do not deal with it
setColorFilter: Set up a color filter , So before you draw it , Each pixel of the drawn content is changed by the color filter
getOpacity: Get opacity , Its value can be determined according to setAlpha Adjust the value set in . such as ,
alpha == 0 Is set to PixelFormat.TRANSPARENT
stay alpha == 255 Is set to PixelFormat.OPAQUE;
Set to at other times PixelFormat.TRANSLUCENT
PixelFormat.OPAQUE: Is completely opaque , Everything under him
PixelFormat.TRANSPARENT: transparent , Nothing at all
PixelFormat.TRANSLUCENT: Only the drawing places cover the contents below
There are two other methods :
getIntrinsicWidth
getIntrinsicHeight
Get internal width and height , Mainly in order to View Use wrap_content When , The size returned using these two methods
Next, let's look at our specific implementation :
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();// Initialize medal brush
initThirdPaint();// Initialize medal level brush
}
To draw bitmap, First, you need to pass in a resource id, Then came the text to be drawn on the right
The numbers on the left are written to death when we demonstrate here
Then it is to set drawable And initialize the brush
You need to initialize two kinds of brushes , Draw the left and right text respectively , A stroked effect , One without stroke effect
Finally, let's talk about how to achieve the stroke effect
In fact, the principle is very simple
Is to draw a text with a thicker stroke below
Then draw a relatively thin stroke on the same surface
The method used is to set the brush stroke thickness :
mStrokePaint.setStrokeWidth(4); // Set the stroke width
As for the text placement
It is set when drawing text
Finally, let's look at the source code
Source code
public class MedalDrawable extends Drawable {
private Bitmap mBitmap;
private String mText;
protected Context mContext;
Paint.FontMetricsInt fontMetrics;
int marginLeft = 62;// Text distance left margin
int strokeMarginLeft = 0;// Stroke text distance left margin
int textSize = 20;// Text size
private Paint mPaint;
private Rect bounds;
private String mThirdText="21";
private Paint mThirdPaint;// Medal Rank number
private Paint mStrokePaint;// Word stroke
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();// Initialize medal brush
initThirdPaint();// Initialize medal level brush
}
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); // Set the stroke width
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) {
// Draw medal text
int baseline = (getIntrinsicHeight() - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.drawText(mText, marginLeft, baseline, mPaint);
// Draw stroke text
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();
}
}
边栏推荐
- c#的初步认识
- After working in a large factory for ten years with an annual salary of 400000 yuan, I was suddenly laid off. If the company wanted to abandon you, it wouldn't leave any kindness
- Index +sql exercise optimization
- The 6th Blue Bridge Cup
- 洛谷刷题心得记录
- Helix QAC is updated to 2022.1 and will continue to provide high standard compliance coverage
- [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,
- lvgl使用demo及说明2
- 【论文阅读】Intrinsically semi-supervised methods
- 【批处理DOS-CMD命令-汇总和小结】-将文件夹映射成虚拟磁盘——subst
猜你喜欢
JVM层次上的对象的创建过程和内存布局
L'introduction en bourse de Wild Wind Pharmaceutical a pris fin: Yu pinzeng, qui avait l'intention de lever 540 millions de RMB, a effectué un investissement P2P.
Redis的持久化机制
【批处理DOS-CMD命令-汇总和小结】-将文件夹映射成虚拟磁盘——subst
SPARQL basic introductory exercise
Redis master-slave replication and sentinel mode
关联GIS:条条道路通UE5城
【13. 二进制中1的个数、位运算】
Read datasets iteratively with xgboost
Redis五种基本类型
随机推荐
Mapping of Taobao virtual product store opening tutorial
Etcd教程 — 第五章 Etcd之etcdctl的使用
Linux下Redis的安装
c#的初步认识
win命令行中导入、导出数据库相关表
闭包问题
PayPal account has been massively frozen! How can cross-border sellers help themselves?
[10. difference]
SQL Sever column name or number of supplied values does not match the table definition
Experience record of Luogu's topic brushing
准备好迁移上云了?请收下这份迁移步骤清单
Filter filter
直接修改/etc/crontab 文件内容,定时任务不生效
参考 | 升级 Win11 移动热点开不了或者开了连不上
Index +sql exercise optimization
Time function calculation efficiency of C
并发编程JUC的AQS底层源码
Associated GIS: all roads lead to ue5 City
Code source AQS sous - jacent pour la programmation simultanée juc
ACM course term summary