視訊直播系統原始碼,使用自定義UI 完成文字顏色載入效果
阿新 • • 發佈:2022-05-25
視訊直播系統原始碼,使用自定義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 完成文字顏色載入效果, 更多內容歡迎關注之後的文章