版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010356768/article/details/89674754
res下新增attrs.xml
<resources>
<declare-styleable name="Shade">
<attr name="text" format="string"/>
<attr name="text_color" format="color"/>
<attr name="shade_color" format="color"/>
<attr name="text_size" format="float"/>
</declare-styleable>
</resources>
activity_main中布局使用
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:Shade="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.xx.shadeview.ShadeView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Shade:text="运动伙伴 就选酷跑"
Shade:text_color="#FF0000FF"
Shade:shade_color="#FF888888"
Shade:text_size="48"/>
</LinearLayout>
MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
ShadeView
public class ShadeView extends View {
String text;
int textColor,shadeColor;
float textSize;
int shadeSize;//阴影大小
int textHeight;//文字的高度
int viewWidth,viewHeight;
public ShadeView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.Shade);
text = typedArray.getString(R.styleable.Shade_text);
textColor = typedArray.getColor(R.styleable.Shade_text_color, Color.BLACK);
shadeColor = typedArray.getColor(R.styleable.Shade_shade_color,Color.BLACK);
textSize = typedArray.getFloat(R.styleable.Shade_text_size,18);
shadeSize = (int)textSize /10;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
try {
//得到文字的大小
Paint paint = new Paint();
paint.setTextSize(textSize);
Rect rect = new Rect();
paint.getTextBounds(text,0,text.length(),rect);
//文字的高度就是矩形的高度
textHeight = rect.height();
//矩形的高度就是文字的高度
viewHeight = rect.height();
viewWidth = rect.width();
//是文字大小+阴影大小
viewHeight+=shadeSize;
viewHeight+=shadeSize;
//设置控件大小
setMeasuredDimension(viewWidth,viewHeight);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.CYAN);
Rect backgroundRect = new Rect(0,0,viewWidth,viewHeight);
canvas.drawRect(backgroundRect,paint);
paint.setTextSize(textSize);
//后画的展示在前面,所以先画阴影
//画阴影
paint.setColor(shadeColor);
canvas.drawText(text,0+shadeSize,textHeight+shadeSize,paint);
//画文字
paint.setColor(textColor);
canvas.drawText(text,0,textHeight,paint);
}
}