Coding & Programming/C, C++, SFML

[C/C++, SFML] 5. 캐릭터, 배경 등 이미지(Texture, Sprite) 출력하기

mainCodes 2021. 3. 28. 17:56

안녕하세요 JollyTree입니다 (•̀ᴗ•́)و

 

지난 시간에 이어 이번에는 배경 또는 캐릭터 이미지를 읽어서 화면에 출력하는 클래스인 Texture, Sprite 클래스에 대해 정리합니다. Texture, Sprite 클래스는 아래 그림과 같이 화면에 파일로 부터 읽은 png, jpg 등의 이미지 파일을 임의 위치에 표현할 수 있는 기능을 제공합니다.

 

Texture, Sprite를 이용한 이미지 출력 화면

 

Texture는 파일로 부터 읽어 들인 이미지를 뜻하고 Sprite는 사각형, 원, 삼각형 등의 모양 틀에 Texture를 입힌 것으로 

개념을 설명하고 있습니다. 예제 코드를 통해서도 알수 있듯이 Sprite는 이미지 데이터(Texture)를 가지고 목적에 맞게 어떻게 Texture를 그려낼지 결정합니다.  SFML 사이트에서도 "A sprite is nothing more than a textured rectangle."로 정리하고 있습니다.

 

Texture color_off;

color_off.loadFromFile("colors_off.png");
...

Sprite sprite;

sprite.setTexture(color_off);  //Texture로 Sprite 셋팅
sprite.setTextureRect(IntRect(0, 0, 504, 504)); 
...

Texture는 기본적으로 그래픽 카드의 메모리에 이미지를 적재하고 Sprite는 Texture를 이용하여 크기, 색, 위치, 로테이션 등을 지정하여 화면에 표현합니다. 

 

Texture, Sprite를 이용한 이미지 출력 예제 소스코드:

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
#include <SFML/Graphics.hpp>
#include <iostream>
 
using namespace std;
using namespace sf;
 
int main()
{
    Clock clock; //경과 시간을 측정할 수있는 Clock객체 선언
    Clock ai_timer;
    float interval = 0, delay1 = 4.0;
    int   count = 0;
 
    const Time ai_time = seconds(0.5f);
 
    cout << "프로그램이 시작되었습니다." << endl;
 
    Texture color_off, color_on;
    Sprite sprite_off, sprite_on;
 
    //이미지 파일 읽기
    color_on.loadFromFile("resources/colors_on.png");
    color_off.loadFromFile("resources/colors_off.png");
 
    //Sprite 셋팅
    sprite_on.setTexture(color_on);
    sprite_on.setTextureRect(IntRect(00504504));
 
    sprite_off.setTexture(color_off);
    sprite_off.setTextureRect(IntRect(00504504));
 
    //화면 크기, 캡션 이름 설정
    RenderWindow app(VideoMode(504504), "https://maincodes.tistory.com/");
    
    //초당 60 프레임 설정
    app.setFramerateLimit(60);  
 
    //SFML 메인 루프 - 윈도우가 닫힐때 까지 반복
    while (app.isOpen())
    {
        //초단위로 경과시간을 구함
        //밀리초는 asMilliseconds(), 마이크로초의 asMicroseconds()메소드 이용
        float time = clock.getElapsedTime().asSeconds();
        clock.restart();
 
        interval += time;
 
        Event event;
        //이벤트 처리
        while (app.pollEvent(event)) {
            //프로그램 종료 이벤트 처리
            if (event.type == Event::EventType::Closed)
            {
                app.close();
                cout << "프로그램이 종료되었습니다." << endl;
            }
        }
 
        //0.5초 마다 시계 재시작
        if (ai_timer.getElapsedTime() > ai_time)
        {
            ai_timer.restart();
            cout << "ai_timer 재시작" << endl;
        }
 
 
        //4초 단위로 interval 초기화, count +1 증가
        if (interval > delay1)
        {
            cout << "interval = " << interval << " count = " << count << endl;
            interval = 0;
            count++;
        }
 
        //스프라이트 변경
        if (((int)interval % 2== 0)
            app.draw(sprite_on);
        else
            app.draw(sprite_off);
 
        //프레임을 스크린에 출력
        app.display();
    }
 
    return 0;
}
cs

 

예제는 2개의 그림 파일(colors_on.png, colors_off.png) 파일을 읽고 if (((int)interval % 2== 0) 조건에 따라 약 1초 단위로 sprite_on과 sprite_off를 화면에 출력합니다.

 

실행결과(Output):

오늘은 Texture, Sprite 클래스를 이용하여 캐릭터, 배경 등에 사용되는 이미지를 화면에 표현하는 방법을 정리하였습니다. 이상 JollyTree였습니다 (•̀ᴗ•́)و