效果图,内容文字可自行修改,颜色如果想自定义追加下就好。文字颜色也可以自定义属性自己在添加下就可以
- package com.fawersmart.engineer.View;
-
- import android.content.Context;
- import android.content.res.TypedArray;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.graphics.Path;
- import android.graphics.RectF;
- import android.util.AttributeSet;
- import android.view.View;
-
- import com.fawersmart.engineer.R;
-
- public class RectangleWithTriangleView extends View {
- private Paint paint;
- private Paint textPaint;
- private Path path;
- private String customText;
-
- public RectangleWithTriangleView(Context context) {
- super(context);
- init(null);
- }
- public RectangleWithTriangleView(Context context, AttributeSet attrs) {
- super(context, attrs);
- init(attrs);
- }
-
- public RectangleWithTriangleView(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- init(attrs);
- }
-
- private void init(AttributeSet attrs) {
- paint = new Paint();
- paint.setColor(Color.BLUE);
- paint.setStyle(Paint.Style.FILL);
- paint.setAntiAlias(true);
- textPaint = new Paint();
- textPaint.setColor(Color.WHITE);
- textPaint.setStyle(Paint.Style.FILL);
- textPaint.setAntiAlias(true);
- textPaint.setTextSize(28); // 文字大小,可以根据需要进行调整
-
- path = new Path();
- rectF = new RectF();
- TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomView);
- customText = typedArray.getString(R.styleable.CustomView_customText);
- }
- private RectF rectF;
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
-
- int width = getWidth();
- int height = getHeight();
- int triangleHeight = width / 10; // 三角形的高度为矩形宽度的四分之一
- int cornerRadius = 10; // 圆角半径,可以根据需要进行调整
-
- // 更新圆角矩形的位置和大小
- rectF.set(0, 0, width, height - triangleHeight);
- // 绘制圆角矩形
- canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, paint);
-
- // 绘制倒三角
- // 绘制倒三角形
- path.reset();
- path.moveTo(0, 5);
- path.lineTo(width, 5);
- path.lineTo(width / 2f, height);
- path.close();
-
- canvas.drawPath(path, paint);
- // 绘制文字
- float textWidth = textPaint.measureText(customText);
- float x = rectF.centerX() - textWidth / 2;
- float y = rectF.centerY() - (textPaint.descent() + textPaint.ascent()) / 2;
- canvas.drawText(customText, x, y, textPaint);
-
-
- }
-
- private float dpToPx(float dp) {
- return dp * getResources().getDisplayMetrics().density;
- }
- }
在res/values/attrs.xml文件中定义自定义属性:
- <resources>
- <declare-styleable name="CustomView">
- <attr name="customText" format="string" />
- <attr name="customTextColor" format="color" />
- </declare-styleable>
- </resources>
引用
- <com.fawersmart.engineer.View.RectangleWithTriangleView
- android:layout_width="36dp"
- android:layout_marginLeft="2dp"
-
- app:customText="text!"
- android:layout_height="18dp"/>