SDL2.0_05_sprite sheet

裁剪。单击键盘1~4键观察图像的不同区域。

全局变量可以改成局部变量,这里懒得改了,有需要的直接看原文。

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;

#include <SDL.h>
#include <SDL_image.h>

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

SDL_Window *win = nullptr;
SDL_Renderer *ren = nullptr;

SDL_Texture * LoadImage(string file) {
	SDL_Texture *tex = nullptr;
	tex = IMG_LoadTexture(ren, file.c_str());
	if (tex == nullptr) {
		cout << "Fail to load image in function LoadImage()!" << endl;
	}

	return tex;
}

void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, SDL_Rect dst, SDL_Rect *clip = nullptr) {
	SDL_RenderCopy(ren, tex, clip, &dst);
}

void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, SDL_Rect *clip = nullptr) {
	SDL_Rect dst;
	dst.x = x;
	dst.y = y;
	if (clip != nullptr) {
		dst.w = clip->w;
		dst.h = clip->h;
	}
	else 
		SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h);
	renderTexture(tex, ren, dst, clip);
}

int main(int argc, char** argv)
{
	if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
		cout << SDL_GetError() << endl;
		return 0;
	}

	win = SDL_CreateWindow("05:", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_RESIZABLE);

	if (win == nullptr) {
		cout << SDL_GetError() << endl;
		return 0;
	}
	
	ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (ren == nullptr) {
		cout << SDL_GetError() << endl;
		return 0;
	}


	SDL_Texture *bg = LoadImage("f:/material/giantShadowFlash.jpg");

	if (bg == nullptr) {
		cout << "Could not load one of the images!" << endl;
		return 0;
	}

	SDL_RenderClear(ren);

	int bw = 100, bh = 100;

	SDL_Rect clips[4];
	for (int i = 0; i < 4; i++) {
		clips[i].x = i / 2 * bw;
		clips[i].y = i % 2 * bh;
		clips[i].w = bw;
		clips[i].h = bh;
	}
	int useClip = 0;

	SDL_Event e;
	bool quit = false;
	while (!quit) {
		while (SDL_PollEvent(&e))
		{
			if (e.type == SDL_QUIT) {
				cout << "quit..." << endl;
				quit = true;
			}
			if (e.type == SDL_KEYDOWN) {
				switch (e.key.keysym.sym) {
				case SDLK_1:
					useClip = 0;
					break;
				case SDLK_2:
					useClip = 1;
					break;
				case SDLK_3:
					useClip = 2;
					break;
				case SDLK_4:
					useClip = 3;
					break;
				default:
					break;
				}
			}
		}
		SDL_RenderClear(ren);
		renderTexture(bg, ren, SCREEN_WIDTH/2 - bw/2, SCREEN_HEIGHT/2 - bh/2, &clips[useClip]);
		SDL_RenderPresent(ren);
	}

	SDL_DestroyTexture(bg);
	SDL_DestroyRenderer(ren);
	SDL_DestroyWindow(win);
	SDL_Quit();
	IMG_Quit();

	cout << "Success!" << endl;
	return 0;
}


 

你可能感兴趣的:(sdl)