Android特殊字体引入,以及描边和投影
标签(空格分隔): Android 字体 描边
这篇文章并非纯原创,因为项目原因,忘记记载出处,还望原作者海涵。
主要功能就是实现了特殊字体的描边
字体文件放在Asset文件夹中
public class GoldTextView extends TextView {
TextPaint m_TextPaint;
int mInnerColor;
int mOuterColor;
public GoldTextView(Context context,int outerColor,int innnerColor) {
super(context);
m_TextPaint = this.getPaint();
this.mInnerColor = innnerColor;
this.mOuterColor = outerColor;
}
public GoldTextView(Context context, AttributeSet attrs) {
super(context, attrs);
m_TextPaint = this.getPaint();
//获取自定义的XML属性名称
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StrokeTextView);
//获取对应的属性值
this.mInnerColor = a.getColor(R.styleable.StrokeTextView_innnerColor,0xffffff);
this.mOuterColor = a.getColor(R.styleable.StrokeTextView_outerColor,0xffffff);
}
public GoldTextView(Context context, AttributeSet attrs, int defStyle,int outerColor,int innnerColor) {
super(context, attrs, defStyle);
m_TextPaint = this.getPaint();
this.mInnerColor = innnerColor;
this.mOuterColor = outerColor;
// TODO Auto-generated constructor stub
}
private boolean m_bDrawSideLine = true; // 默认采用描边
/**
*
*/
@Override
protected void onDraw(Canvas canvas) {
if (m_bDrawSideLine) {
// 描外层
// super.setTextColor(Color.BLUE); // 不能直接这么设,如此会导致递归
setTextColorUseReflection(mOuterColor);
m_TextPaint.setStrokeWidth(8); // 描边宽度
m_TextPaint.setStyle(Paint.Style.FILL_AND_STROKE); // 描边种类
m_TextPaint.setFakeBoldText(true); // 外层text采用粗体
m_TextPaint.setShadowLayer(1, 0, 0, 0); // 字体的阴影效果,可以忽略
super.onDraw(canvas);
// 描内层,恢复原先的画笔
// super.setTextColor(Color.BLUE); // 不能直接这么设,如此会导致递归
setTextColorUseReflection(mInnerColor);
m_TextPaint.setStrokeWidth(0);
m_TextPaint.setStyle(Paint.Style.FILL_AND_STROKE);
m_TextPaint.setFakeBoldText(false);
m_TextPaint.setShadowLayer(0, 0, 0, 0);
}
super.onDraw(canvas);
}
/**
* 使用反射的方法进行字体颜色的设置
* @param color
*/
private void setTextColorUseReflection(int color) {
Field textColorField;
try {
textColorField = TextView.class.getDeclaredField("mCurTextColor");
textColorField.setAccessible(true);
textColorField.set(this, color);
textColorField.setAccessible(false);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
m_TextPaint.setColor(color);
}
}
xml文件
<GoldTextView
android:layout_marginTop="@dimen/y125"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="仅仅是个测试"
android:shadowColor="#9d4e0c"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="10"
android:textSize="19sp"
android:layout_gravity="center_horizontal|top"
android:textColor="#ffe226"
app:outerColor="#9d4e0c"
app:innnerColor="#ffe226"
android:paddingTop="@dimen/x520"
android:id="@+id/gold_info_tv"/>