[英]How to draw ellipse's arc on android?
我想在我的 android 應用程序中繪制一條橢圓弧。 我使用了這個代碼:
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
angle=45; //angle of ellipse major axis with X-axis.
startAngle=0; //start angle of arc
sweepAngle=90; //sweep angle of arc
a = 200; //major axis of ellipse
b = 100; //minor axis of ellipse
canvas.rotate(angle, center.x, center.y);
//draw the arc
canvas.drawArc(rect, startAngle - angle, sweepAngle, true, paintLine);
paintLine.setPathEffect(new DashPathEffect(new float[] { 5, 5 }, 0));
canvas.drawOval(rect, paintLine);
canvas.restore();
paintLine.setPathEffect(null);
}
我收到這個形狀:
我需要的弧應該在此圖像的紅點處開始和結束:
請告訴我我犯了什么錯誤。
謝謝。
當 android 繪制橢圓弧時,就好像它首先在提供的掃掠角上繪制圓弧一樣。 然后它縮放這個圓弧,使其適合指定的橢圓。 橢圓的起始角和掃描角將與指定的起始角和掃描角不同。 要獲得想要的角度,必須將實際角度指定為 tan(actual-angle) = (a/b)*tan(wanted-angle)
public class Main3Activity extends Activity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = new View(this) {
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
float angle=45; //angle of ellipse major axis with X-axis.
// These are the wanted angles
float startAngle_ = (float)Math.toRadians(315); //start angle of arc
float endAngle_ = (float)Math.toRadians(45); //end angle of arc
float a = 200; //major axis of ellipse
float b = 100; //minor axis of ellipse
float xc = getWidth()/2f;
float yc = getHeight()/2f;
// These are the angles to use
float startAngle = (float)Math.toDegrees(
Math.atan2(a*Math.sin(startAngle_),b*Math.cos(startAngle_)));
float endAngle = (float)Math.toDegrees(
Math.atan2(a*Math.sin(endAngle_),b*Math.cos(endAngle_)));
float sweepAngle = endAngle - startAngle;
RectF rect = new RectF(xc-a,yc-b,xc+a,yc+b);
Paint paintLine = new Paint(Paint.ANTI_ALIAS_FLAG);
paintLine.setStyle(Paint.Style.STROKE);
canvas.rotate(angle,xc,yc);
//draw the arc
canvas.drawArc(rect, startAngle, sweepAngle, true, paintLine);
paintLine.setPathEffect(new DashPathEffect(new float[] { 5, 5 }, 0));
canvas.drawOval(rect, paintLine);
canvas.restore();
paintLine.setPathEffect(null);
}
};
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
addContentView(view,layout);
}
這個問題已經快七年了! 是時候更新文檔了?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.