视频直播系统源码,使用自定义UI 完成文字颜色加载效果
1、自定义文本属性
在项目attrs.xml 文件中 res -> values -> attrs.xml,自定义文本属性,没有这个文件,就新建一个。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ColorTrackTextView">
<attr name="originColor" format="color" />
<attr name="changeColor" format="color" />
</declare-styleable>
</resources>
2、创建组件
新建一个 ColorTrackTextView 文件,继承自 AppCompatTextView 这里也可以直接继承View,我只需要自定义TextView ,就直接继承 AppCompatTextView
public class ColorTrackTextView extends AppCompatTextView {
// 绘制不变色字体的画笔
private Paint mOriginPaint;
// 绘制变色字体的画笔
private Paint mChangePaint;
public ColorTrackTextView(@NonNull Context context) {
this(context, null);
}
public ColorTrackTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ColorTrackTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
3、在 xml 中使用组件
<com.traveleasy.leaningui.ColorTrackTextView
android:id="@+id/color_track_tv"
android:text="Hello Word"
android:textSize="20sp"
app:changeColor="@color/teal_200"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints" />
上面的三步中,已经完成了自定义TextView 的属性设置,以及在 xml 中使用,接下来开始做测量绘制的效果
4、测量
这里我直接继承的是 AppCompatTextView, 所以就直接跳过了测量部分。当然,如果继承的是View,也只需要测量自己就可以了
5、绘制
接下来通过 onDraw:绘制,在此之前,我们需要先创建一个画笔
/**
* 根据颜色,设置画笔
*
* @return
*/
private Paint getPaintByColor(int color) {
Paint paint = new Paint();
// 设置颜色
paint.setColor(color);
// 设置抗锯齿
paint.setAntiAlias(true);
// 防抖动
paint.setDither(true);
// 设置字体的大小 就是TextView 文本字体大小
paint.setTextSize(getTextSize());
return paint;
}
画笔中的颜色,我传入即可
这里我初始了两个画笔颜色,一个默认颜色,和一个需要变成的颜色
// 绘制不变色字体的画笔
private Paint mOriginPaint;
// 绘制变色字体的画笔
private Paint mChangePaint;
需要先初始化一个 TypedArray,在使用 TypedArray 时候,别忘了回收哦
private void initPaint(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ColorTrackTextView);
int changeColor = typedArray.getColor(R.styleable.ColorTrackTextView_changeColor, getTextColors().getDefaultColor());
int originColor = typedArray.getColor(R.styleable.ColorTrackTextView_originColor, getTextColors().getDefaultColor());
// typedArray 回收
typedArray.recycle();
// 不变颜色的画笔
mOriginPaint = getPaintByColor(originColor);
// 变色的画笔
mChangePaint = getPaintByColor(changeColor);
}
以上就是视频直播系统源码,使用自定义UI 完成文字颜色加载效果, 更多内容欢迎关注之后的文章