android textview 楷体,Android自定义控件之自定义Text,画出米字格-FenGKun

该博客介绍了一个自定义的WordText类,继承自TextView,用于在Android中绘制带有虚线效果的文字。通过设置画笔属性、路径效果以及读取自定义属性,实现了文字的虚线显示,并支持楷体字体和颜色定制。示例代码展示了如何在布局文件中使用该自定义视图。
摘要由CSDN通过智能技术生成

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(TypedValue.COMPLEX_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="http://schemas.android.com/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"

/>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值