public class WordText extends TextView {
/** 画笔 */
private Paint paint = new Paint(); // 定义画笔
public WordText(Context context) {
super(context);
init(null);
}
public WordText(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public WordText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
private void init(AttributeSet attrs) {
// 初始化画笔
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE); // STROKE不填充,FILL填充,.FILL_AND_STROKE设置线条的样式,把空心线填满
PathEffect effects = new DashPathEffect(new float[]{5, 5, 5, 5}, 1);
paint.setPathEffect(effects);
// 根据用户配置的参数设置米字的颜色
if (attrs != null) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.WordText);
// 获取米字背景颜色,并设置到UI
int iDottedLineColor = typedArray.getColor(R.styleable.WordText_DottedLineColor, Color.RED);
paint.setColor(iDottedLineColor);
boolean isKaiTi = typedArray.getBoolean(R.styleable.WordText_IsKaiTi, false);
// 设置字体为楷体
if (isKaiTi) {
setTypeface(MyApplication.m_tfSTKaiTi);
}
typedArray.recycle();
}
else {
paint.setColor(Color.RED);
}
}
@Override
protected void onDraw(Canvas canvas) {
// 字大小与控件高的比例计算出字体的大小(单位像素)
setTextSize(PLEX_UNIT_PX, getHeight() * 0.67f);
// 左上至右下线
drawDottedLine(0, 0, getWidth(), getHeight(), canvas);
// 纵向线
drawDottedLine(getWidth() / 2, 0, getWidth() / 2, getHeight(), canvas);
// 右上至坐下
drawDottedLine(getWidth(), 0, 0, getHeight(), canvas);
// 水平线
drawDottedLine(0, getHeight() / 2, getWidth(), getHeight() / 2, canvas);
super.onDraw(canvas);
}
/**
* 画虚线
*/
private void drawDottedLine(int startX, int startY, int endX, int endY, Canvas canvas) {
Path path = new Path();
path.moveTo(startX, startY);
path.lineTo(endX, endY);
canvas.drawPath(path, paint);
}
}
自定义样式
android:shape="rectangle" >
布局文件中调用
xmlns:mc="/apk/res/com.miisi.nc.magicchinese"
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#232187" >
<com.miisi.nc.magicchinese.view.WordText android:id="@+id/tvWord"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="223"
mc:DottedLineColor="#FFF"
mc:IsKaiTi="true"
android:text="日"
android:textSize="120dp"
android:textColor="#fff"
android:gravity="center"
android:background="@drawable/bg_style_frame_white_no_solid"
/>