在项目的弹窗页有倒三角形指示的设计图,如下:
最方便的做法就是要求切一张倒三角的图出来,我这里用的代码实现方法,先自定义一个三角形TriangleView,代码如下:
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.View; public class TriangleView extends View { private int width = Utils.dp2px(20);//将dp转成px的方法... private int height = Utils.dp2px(10); private Paint whitePaint; private Path path; public TriangleView(Context context) { this(context, null); } public TriangleView(Context context, AttributeSet attrs) { super(context, attrs); whitePaint = new Paint(); whitePaint.setAntiAlias(true); whitePaint.setColor(Color.WHITE); whitePaint.setStyle(Paint.Style.FILL); path = new Path(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); width = measureLength(widthMeasureSpec, width); height = measureLength(heightMeasureSpec, height); setMeasuredDimension(width, height); } private int measureLength(int measureSpec, int length) { int measureLength = 0; int mode = MeasureSpec.getMode(measureSpec); int size = MeasureSpec.getSize(measureSpec); switch (mode) { case MeasureSpec.AT_MOST: //wrap_content时size其实为父控件能给的最大长度,length相关于一个默认值的作用 Math.min measureLength = Math.min(size, length); break; case MeasureSpec.EXACTLY: //match_parent或指定如30dp时 测出来多大就多大,考虑的情况是有时候测量出的确没有空间放置此控件了 measureLength = size; break; case MeasureSpec.UNSPECIFIED: measureLength = length; break; } return measureLength; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawTriangle(canvas); } private void drawTriangle(Canvas canvas) { //用路径来画出这个三角形path.moveTo(0, 0);//起始点 path.lineTo(width, 0);//从起始点画一根线到 相应的坐标 path.lineTo((float) width / 2, height); path.close();//闭合 canvas.drawPath(path, whitePaint);}}
在res/layout里.xml文件用的时候需要注意一下,这是我的代码实现方式,为了效果我增加了层次:<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/transparent" android:orientation="horizontal"> <View android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" /> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <com.test.TriangleView android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout>
最后提一下,如果你copy后的话,Utils.dp2px这个方法是需要你自己实现的
还有注意一点,引用自定义TriangleView的时候需要注意前缀的包名是否正确