[Godot] Line2D 선 그리기

Godot 2024. 2. 21. 18:02 |
반응형

간단한 선을 그려보자.

 

Line2D 노드 두 개와 스크립트를 추가한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using Godot;
using System.Collections.Generic;
 
public partial class Control : Node2D
{
    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
        DrawCircle();
        DrawPentagram();
    }
 
    // 원 그리기
    public async void DrawCircle()
    {
        Line2D line = GetNode<Line2D>("Line2D");
        //line.Closed = true;
        // Closed를 여기서 변경하면 원이 그려지는 방식이 달라진다.
        line.Width = 2;
        line.DefaultColor = Colors.Red;
        line.Position = new Vector2(200200);
 
        float radius = 100;
        float angle;
 
        for (int i = 0; i < 360; i++)
        {
            angle = Mathf.DegToRad(i);
            line.AddPoint(CalcCirclePoint(radius, angle));
            await ToSignal(GetTree().CreateTimer(0.01), SceneTreeTimer.SignalName.Timeout);
        }
 
        line.Closed = true;
    }
 
    // 원 포인트 계산
    public Vector2 CalcCirclePoint(float radius, float angle)
    {
        float x = Mathf.Cos(angle);
        float y = Mathf.Sin(angle);
 
        return new Vector2(x * radius, y * radius);
    }
 
    // 별 그리기
    public async void DrawPentagram()
    {
        Line2D line = GetNode<Line2D>("Line2D2");
        line.Width = 2;
        line.DefaultColor = Colors.Blue;
        line.Position = new Vector2(200200);
 
        List<Vector2> points = new List<Vector2>();
        points.Add(new Vector2(6080));
        points.Add(new Vector2(0-100));
        points.Add(new Vector2(-6080));
        points.Add(new Vector2(95-25));
        points.Add(new Vector2(-95-25));
        //points.Add(new Vector2(60, 80));
        // 마지막에 Closed 프로퍼티에 true를 대입하기 때문에 별의 시작점을 다시 추가할
        // 필요는 없다.
 
        for (int i = 0; i < points.Count; i++)
        {
            line.AddPoint(points[i]);
            await ToSignal(GetTree().CreateTimer(1), SceneTreeTimer.SignalName.Timeout);
        }
 
        line.Closed = true;
    }
}
 

 

위와 같이 코드를 작성한다.

 

 

※ 참고

Line2D

Custom drawing in 2D

 

반응형
Posted by J-sean
:
반응형

Create a simple drawing app for Android.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }
 
    public class MyView extends View {
        Paint paint = new Paint();
        boolean isDrawing = false;
        ArrayList<Float> coordinateList = new ArrayList<>(100);
        // Each ArrayList instance has a capacity. The capacity is the size of the array used to store
        // the elements in the list. It is always at least as large as the list size. As elements are
        //  added to an ArrayList, its capacity grows automatically. The details of the growth policy
        //  are not specified beyond the fact that adding an element has constant amortized time cost.
 
        MyView(Context context)
        {
            super(context);
            paint.setColor(Color.BLUE); // 0xff0000ff
            paint.setStrokeWidth(8);
        }
 
        @Override
        public void onDraw(Canvas canvas)
        {
            // ArrayList, Float[], float[]은 서로 직접 호환되지 않음.
            Float[] coordinateFloat = coordinateList.toArray(new Float[coordinateList.size()]);
            float[] coordinate = new float[coordinateFloat.length];
 
            for (int i = 0; i < coordinateFloat.length; i++)
            {
                coordinate[i] = coordinateFloat[i].floatValue();
            }
 
            // 특정 색으로 화면을 채우는 메서드
            // void drawRGB(int r, int g, int b)
            // void drawARGB(int a, int r, int g, int b)
            // void drawColor(int color)
            // void drawPaint(Paint paint)
            canvas.drawARGB(2552552550); // Yellow
            canvas.drawLines(coordinate, paint);
            // Draw a series of lines. Each line is taken from 4 consecutive values in the pts array.
            // Thus to draw 1 line, the array must contain at least 4 values. This is logically the
            // same as drawing the array as follows: drawLine(pts[0], pts[1], pts[2], pts[3]) followed
            // by drawLine(pts[4], pts[5], pts[6], pts[7]) and so on.
        }
 
        // drawLines()는 4개의 좌표를 이용해 1개의 직선을 그린다(x1, y1, x2, y2)
        // 1개의 직선을 그리고 다음 직선의 시작 좌표(x1, y1)에 이전 끝 좌표(x2, y2)가
        // 없다면 끊어진 선으로 그려지게 된다. 마우스를 뗄때는 다음 직선의 시작 좌표로
        // 넣어준 값 두 개(x1, y1)를 삭제 해야 한다.
        @Override
        public boolean onTouchEvent(MotionEvent event)
        {
            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    coordinateList.add(event.getX());
                    coordinateList.add(event.getY());
                    isDrawing = true;
                    break;
 
                case MotionEvent.ACTION_MOVE:
                    if (isDrawing)  // 이 코드에서는 별 의미는 없는 if
                    {
                        coordinateList.add(event.getX());
                        coordinateList.add(event.getY());
 
                        coordinateList.add(event.getX());
                        coordinateList.add(event.getY());
                    }
 
                    invalidate();
                    break;
 
                case MotionEvent.ACTION_UP:
                    coordinateList.remove(coordinateList.size() -1);
                    coordinateList.remove(coordinateList.size() -1);
                    isDrawing = false;
                    break;
 
                default:
                    break;
            }
 
            return true;
        }
    }



Run the app and draw.



To simplify the code, you can also use Path. The result is the same.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }
 
    public class MyView extends View {
        Paint paint = new Paint();
        boolean isDrawing = false;
        Path path = new Path();
 
        MyView(Context context)
        {
            super(context);
            paint.setColor(Color.BLUE); // 0xff0000ff
            paint.setStyle(Paint.Style.STROKE); // Paint.Style.FILL(기본값)로 하면 채워진 도형이 그려진다
            paint.setStrokeWidth(8);
        }
 
        @Override
        public void onDraw(Canvas canvas)
        {
            canvas.drawARGB(2552552550);
            canvas.drawPath(path, paint);
        }
 
        @Override
        public boolean onTouchEvent(MotionEvent event)
        {
            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    path.moveTo(event.getX(), event.getY());
                    isDrawing = true;
                    break;
 
                case MotionEvent.ACTION_MOVE:
                    if (isDrawing)
                    {
                        path.lineTo(event.getX(), event.getY());
                        invalidate();
                    }
                    break;
 
                case MotionEvent.ACTION_UP:
                    isDrawing = false;
                    break;
 
                default:
                    break;
            }
 
            return true;
        }
    }



반응형
Posted by J-sean
: