안드로이드 개발 질문/답변
(글 수 45,052)
import 뭘 시켜야 되죠?
2010.02.11 10:20:23
간단한 예제 입니다.
안드로이드에서는 왼쪽, 상단이 원점(0,0)입니다.
그래서 그래프를 그리면 그래프모양이 뒤집혀 나옵니다. 이부분은 y값을 반대로 하면 됩니다.
public class DrawGraph extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TestView tv = new TestView(this);
setContentView(tv);
}
}
class TestView extends View
{
public TestView(Context context) {
super(context);
}
public void onDraw(Canvas canvas)
{
Paint p = new Paint(); //그래프의 색
p.setColor(Color.BLUE);
Paint p1 = new Paint(); //기준선의 색, X축, Y축
p1.setColor(Color.RED);
float startingX = 160.0f; //원점 X좌표
float startingY = 240.0f; //원점 Y좌표
canvas.drawLine(0, startingY, 320, startingY, p1); //기준선 X좌표 그리기
canvas.drawLine(startingX, 0, startingX, 480, p1); //기준선 Y좌표 그리기
float x=0.0f, y=0.0f, _y=0.0f; //다음 점의 x, y, -x에 대한 y값
float x1=x, y1=y, _y1=_y; //이전 점의 x, y, -x에 대한 y값
//20.0f 는 그래프의 그리는 X값의 범위 -20<= X <=20
//x의 증가값이 작을 수록 곡선이 잘 표현 됨
for(; x<=20.0f; x++)
{
//함수식을 여기에 대입
y = 2*x+10.0f; //x 값이 양수일 때 y값
_y = 2*(-x)+10.0f; //x 값이 음수일 때 y값
canvas.drawLine(x1+startingX, y1+startingY, x+startingX, y+startingY, p); //양수 그래프 그리기
canvas.drawLine(-x1+startingX, _y1+startingY, -x+startingX, _y+startingY, p); //음수 그래프 그리기
x1=x; y1=y; _y1=_y; //그린 후 점의 위치 변경
}
}
}
안드로이드에서는 왼쪽, 상단이 원점(0,0)입니다.
그래서 그래프를 그리면 그래프모양이 뒤집혀 나옵니다. 이부분은 y값을 반대로 하면 됩니다.
public class DrawGraph extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TestView tv = new TestView(this);
setContentView(tv);
}
}
class TestView extends View
{
public TestView(Context context) {
super(context);
}
public void onDraw(Canvas canvas)
{
Paint p = new Paint(); //그래프의 색
p.setColor(Color.BLUE);
Paint p1 = new Paint(); //기준선의 색, X축, Y축
p1.setColor(Color.RED);
float startingX = 160.0f; //원점 X좌표
float startingY = 240.0f; //원점 Y좌표
canvas.drawLine(0, startingY, 320, startingY, p1); //기준선 X좌표 그리기
canvas.drawLine(startingX, 0, startingX, 480, p1); //기준선 Y좌표 그리기
float x=0.0f, y=0.0f, _y=0.0f; //다음 점의 x, y, -x에 대한 y값
float x1=x, y1=y, _y1=_y; //이전 점의 x, y, -x에 대한 y값
//20.0f 는 그래프의 그리는 X값의 범위 -20<= X <=20
//x의 증가값이 작을 수록 곡선이 잘 표현 됨
for(; x<=20.0f; x++)
{
//함수식을 여기에 대입
y = 2*x+10.0f; //x 값이 양수일 때 y값
_y = 2*(-x)+10.0f; //x 값이 음수일 때 y값
canvas.drawLine(x1+startingX, y1+startingY, x+startingX, y+startingY, p); //양수 그래프 그리기
canvas.drawLine(-x1+startingX, _y1+startingY, -x+startingX, _y+startingY, p); //음수 그래프 그리기
x1=x; y1=y; _y1=_y; //그린 후 점의 위치 변경
}
}
}
수학 함수를 쓰시려면 import 필요없이 Math 클래스를 쓰시면 되고
관련된 메서드들은 여기를 참고하세요 전부 static 메서드이기 때문에 인스턴스를 만들지 않습니다.
http://developer.android.com/reference/java/lang/Math.html