import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.View;
public class Slice extends View {
Paint mPaint;
Path mPath;
public enum Direction {
NORTH, SOUTH, EAST, WEST
}
public Slice(Context context) {
super(context);
create();
}
public Slice(Context context, AttributeSet attrs) {
super(context, attrs);
create();
}
public void setColor(int color) {
mPaint.setColor(color);
invalidate();
}
private void create() {
mPaint = new Paint();
mPaint.setStyle(Style.FILL);
mPaint.setColor(Color.RED);
}
@Override
protected void onDraw(Canvas canvas) {
mPath = calculate(Direction.SOUTH);
canvas.drawPath(mPath, mPaint);
}
private Path calculate(Direction direction) {
Point p1 = new Point();
p1.x = 0;
p1.y = 0;
Point p2 = null, p3 = null;
int width = getWidth();
if (direction == Direction.NORTH) {
p2 = new Point(p1.x + width, p1.y);
p3 = new Point(p1.x + (width / 2), p1.y - width);
} else if (direction == Direction.SOUTH) {
p2 = new Point(p1.x + width, p1.y);
p3 = new Point(p1.x + (width / 2), p1.y + width);
} else if (direction == Direction.EAST) {
p2 = new Point(p1.x, p1.y + width);
p3 = new Point(p1.x - width, p1.y + (width / 2));
} else if (direction == Direction.WEST) {
p2 = new Point(p1.x, p1.y + width);
p3 = new Point(p1.x + width, p1.y + (width / 2));
}
Path path = new Path();
path.moveTo(p1.x, p1.y);
path.lineTo(p2.x, p2.y);
path.lineTo(p3.x, p3.y);
return path;
}
}
你的活动(例子) :
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
public class Layout extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Slice mySlice = new Slice(getApplicationContext());
mySlice.setBackgroundColor(Color.WHITE);
setContentView(mySlice, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
}
工作范例:
另一个绝对简单的 Calculate函数,你可能感兴趣. 。
private Path Calculate(Point A, Point B, Point C) {
Path Pencil = new Path();
Pencil.moveTo(A.x, A.y);
Pencil.lineTo(B.x, B.y);
Pencil.lineTo(C.x, C.y);
return Pencil;
}
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:height="100dp"
android:width="100dp"
android:viewportHeight="100"
android:viewportWidth="100" >
<group
android:name="triableGroup">
<path
android:name="triangle"
android:fillColor="#848af8"
android:pathData="M 0,20 L 0,0 L 100,0 L 100,20 L 54,55 l -1,0.6 l -1,0.4 l -1,0.2 l -1,0 l -1,-0 l -1,-0.2 l -1,-0.4 l -1,-0.6 L 46,55 L 0,20 -100,-100 Z" />
</group>
</vector>
定制 xml 设计的整个逻辑在 pathData中。考虑左上角为(0,0) ,并根据您的需求设计布局。
检查 这个应答。