我来晚了,遇到了同样的问题,Google指出了我第一个结果是StackOverflow这个线程。
我尝试使用xml方式添加三角形,并发现一个问题,即通过xml方式的三角形占用的空间比看上去要大。
查看屏幕快照,其中包含布局边界
因此,最终制作了可以绘制以下任何类型的Triangle的自定义视图类:
- 向上指
- 朝下
- 左指向&
- 正确指向
阿萨斯
package com.hiteshsahu.materialupvotewidget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.View;
public class TriangleShapeView extends View {
private int colorCode = Color.DKGRAY;
public int getColorCode() {
return colorCode;
}
public void setColorCode(int colorCode) {
this.colorCode = colorCode;
}
public TriangleShapeView(Context context) {
super(context);
if (isInEditMode())
return;
}
public TriangleShapeView(Context context, AttributeSet attrs) {
super(context, attrs);
if (isInEditMode())
return;
}
public TriangleShapeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (isInEditMode())
return;
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int w = getWidth() / 2;
int h = getHeight() / 2;
//Choose what type of triangle you want here
Path path = getLeftTriangle(w, h);
path.close();
Paint p = new Paint();
p.setColor(colorCode);
p.setAntiAlias(true);
canvas.drawPath(path, p);
}
@NonNull
/**
* Return Path for down facing triangle
*/
private Path getInvertedTriangle(int w, int h) {
Path path = new Path();
path.moveTo(0, 0);
path.lineTo(w, 2 * h);
path.lineTo(2 * w, 0);
path.lineTo(0, 0);
return path;
}
@NonNull
/**
* Return Path for Up facing triangle
*/
private Path getUpTriangle(int w, int h) {
Path path = new Path();
path.moveTo(0, 2 * h);
path.lineTo(w, 0);
path.lineTo(2 * w, 2 * h);
path.lineTo(0, 2 * h);
return path;
}
@NonNull
/**
* Return Path for Right pointing triangle
*/
private Path getRightTriangle(int w, int h) {
Path path = new Path();
path.moveTo(0, 0);
path.lineTo(2 * w, h);
path.lineTo(0, 2 * h);
path.lineTo(0, 0);
return path;
}
@NonNull
/**
* Return Path for Left pointing triangle
*/
private Path getLeftTriangle(int w, int h) {
Path path = new Path();
path.moveTo(2 * w, 0);
path.lineTo(0, h);
path.lineTo(2 * w, 2 * h);
path.lineTo(2 * w, 0);
return path;
}
}
您可以像这样在xml布局中简单地使用它
<com.hiteshsahu.materialupvote.TriangleShapeView
android:layout_width="50dp"
android:layout_height="50dp"></com.hiteshsahu.materialupvote.TriangleShapeView>
我知道OP需要xml解决方案中的解决方案,但是正如我指出的xml方法存在的问题。希望对您有所帮助。