//Using SDL and standard IO
#include <SDL.h>
#include <stdio.h>
#include <SDL_image.h>
const int SCREEN_WIDTH = 840;
const int SCREEN_HEIGHT = 680;
int main(int argc, char* args[])
{
SDL_Init(SDL_INIT_VIDEO); //初始化
//新建窗口
SDL_Window* window = SDL_CreateWindow("SDL Tutoriall", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
SDL_Rect rect;
rect.x = 0;
rect.y = 0;
//找到windows窗口,建立表面
SDL_Surface* surface = SDL_GetWindowSurface(window);
SDL_Surface* cat = IMG_Load("foo.png");
SDL_Event event;
bool quit = false;
while (quit == false) {
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT) {
//printf("Hello\n");
quit = true;
}
else if (event.type == SDL_MOUSEMOTION){
//printf("hello\n");
rect.x = event.motion.x - (cat->w / 2);
rect.y = event.motion.y - (cat->h / 2);
SDL_FillRect(surface, NULL, 0);
SDL_BlitSurface(cat, NULL, surface, &rect);
//刷新窗口
SDL_UpdateWindowSurface(window);
printf("%d, %d\n", rect.x, rect.y);
}
}
}
//保持窗口
//SDL_Delay(2000);
//销毁surface
SDL_FreeSurface(cat);
SDL_FreeSurface(surface);
//销毁窗口
SDL_DestroyWindow(window);
//退出
SDL_Quit();
return 0;
}
实现图片的自行移动
//Using SDL and standard IO
#include <SDL.h>
#include <stdio.h>
#include <SDL_image.h>
const int SCREEN_WIDTH = 840;
const int SCREEN_HEIGHT = 680;
SDL_Rect rect;
bool moveRight = true;
bool moveDown = true;
void updatePosition() {
if (moveRight == true) {
rect.x++;
if (rect.x + rect.w >= SCREEN_WIDTH) {
moveRight = false;
}
}
else {
rect.x--;
if (rect.x <= 0) {
moveRight = true;
}
}
if (moveDown == true) {
rect.y++;
if (rect.y + rect.h >= SCREEN_HEIGHT) {
moveDown = false;
}
}
else {
rect.y--;
if (rect.y <= 0) {
moveDown = true;
}
}
}
int main(int argc, char* args[])
{
SDL_Init(SDL_INIT_VIDEO); //初始化
//新建窗口
SDL_Window* window = SDL_CreateWindow("SDL Tutoriall", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
//创建一个渲染器
SDL_Renderer* rend = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_RenderClear(rend);
SDL_Surface* catSurface = IMG_Load("foo.png");
//把catSurface贴到rend
SDL_Texture* cat = SDL_CreateTextureFromSurface(rend,catSurface);
rect.x = 0;
rect.y = 0;
rect.w = catSurface->w;
rect.h = catSurface->h;
SDL_Event event;
bool quit = false;
while (quit == false) {
while (SDL_PollEvent(&event)){
if (event.type == SDL_QUIT) {
//printf("Hello\n");
quit = true;
}
/*else if (event.type == SDL_MOUSEMOTION){
rect.x = event.motion.x - (catSurface->w / 2);
rect.y = event.motion.y - (catSurface->h / 2);
SDL_RenderClear(rend);
SDL_RenderCopy(rend, cat, NULL, &rect);
}*/
}
updatePosition();
SDL_Delay(5);
SDL_RenderClear(rend);
SDL_RenderCopy(rend, cat, NULL, &rect);
SDL_RenderPresent(rend);
}
//保持窗口
SDL_Delay(2000);
//销毁surface
SDL_FreeSurface(catSurface);
//销毁窗口
SDL_DestroyWindow(window);
//退出
SDL_Quit();
return 0;
}