我在Android工作室使用路径创建钻石形状时遇到了麻烦。看起来我有一半以上的钻石,但我不知道我做错了什么以及为什么其余部分没有打印出来。我一直试图改变我的代码几个小时,没有任何工作。谁能指出我做错了什么?到目前为止,这是我的代码:
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.shapes.Shape;
public class Diamond extends Shape {
private int strokeWidth;
private final int fillColor;
private int strokeColor;
private Path path;
private Paint strokePaint;
private Paint fillPaint;
public Diamond(int strokeWidth, int fillColor, int strokeColor) {
this.strokeWidth = strokeWidth;
this.fillColor = fillColor;
this.strokeColor = strokeColor;
this.strokePaint = new Paint();
this.strokePaint.setStyle(Paint.Style.STROKE);
this.strokePaint.setStrokeWidth(strokeWidth);
this.fillPaint = new Paint();
this.fillPaint.setStyle(Paint.Style.FILL);
this.fillPaint.setColor(fillColor);
}
@Override
public void draw(Canvas canvas, Paint paint) {
canvas.drawPath(path, fillPaint);
canvas.drawPath(path, strokePaint);
}
@Override
protected void onResize(float width, float height) {
super.onResize(width, height);
path = new Path();
path.moveTo(width/2, 0);
path.lineTo(width, height);
path.lineTo(width/2, height*4);
path.lineTo(0, height);
path.close();
}
}
我认为你应该只需要改变path.lineTo(width/2, height*4);
而不是像path.lineTo(width/2, height*2);
那样将高度乘以2,使用4使得下半部分比顶部倾斜更长。还有一个关于this page绘制菱形的例子,你可以通过使用全宽来修改以绘制钻石,例如:
public void drawRhombus(Canvas canvas, Paint paint, int x, int y, int width) {
int halfWidth = width / 2;
Path path = new Path();
path.moveTo(x, y + width); // Top
path.lineTo(x - halfWidth, y); // Left
path.lineTo(x, y - width); // Bottom
path.lineTo(x + halfWidth, y); // Right
path.lineTo(x, y + width); // Back to Top
path.close();
canvas.drawPath(path, paint);
}