-
Notifications
You must be signed in to change notification settings - Fork 21
/
hello3_image.c
79 lines (69 loc) · 2.11 KB
/
hello3_image.c
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
/**
* hello3_image.c - Initializes SDL, loads an image, And displys it in a window
*/
#include <stdio.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_timer.h>
#include <SDL2/SDL_image.h>
int main(void)
{
// attempt to initialize graphics and timer system
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0)
{
printf("error initializing SDL: %s\n", SDL_GetError());
return 1;
}
SDL_Window* win = SDL_CreateWindow("Hello, CS50!",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640, 480, 0);
if (!win)
{
printf("error creating window: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}
// create a renderer, which sets up the graphics hardware
Uint32 render_flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC;
SDL_Renderer* rend = SDL_CreateRenderer(win, -1, render_flags);
if (!rend)
{
printf("error creating renderer: %s\n", SDL_GetError());
SDL_DestroyWindow(win);
SDL_Quit();
return 1;
}
// load the image into memory using SDL_image library function
SDL_Surface* surface = IMG_Load("resources/hello.png");
if (!surface)
{
printf("error creating surface\n");
SDL_DestroyRenderer(rend);
SDL_DestroyWindow(win);
SDL_Quit();
return 1;
}
// load the image data into the graphics hardware's memory
SDL_Texture* tex = SDL_CreateTextureFromSurface(rend, surface);
SDL_FreeSurface(surface);
if (!tex)
{
printf("error creating texture: %s\n", SDL_GetError());
SDL_DestroyRenderer(rend);
SDL_DestroyWindow(win);
SDL_Quit();
return 1;
}
// clear the window
SDL_RenderClear(rend);
// draw the image to the window
SDL_RenderCopy(rend, tex, NULL, NULL);
SDL_RenderPresent(rend);
// wait a few seconds
SDL_Delay(5000);
// clean up resources before exiting
SDL_DestroyTexture(tex);
SDL_DestroyRenderer(rend);
SDL_DestroyWindow(win);
SDL_Quit();
}