type
status
date
slug
summary
tags
category
icon
password
#include <iostream> #include "SDL2/SDL.h" #include "SDL2_image/SDL_image.h" #include "demo_sdl.h" using namespace std; const int WIDTH = 1000; const int HEIGHT = 600; void showImage() { if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { cout << "初始化失败" << endl; return; } SDL_Window *window = SDL_CreateWindow("Show Image", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN); if (window == nullptr) { cout << "创建Window失败:" << SDL_GetError() << endl; return; } SDL_Renderer *renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED); if (renderer == nullptr) { cout << "创建Renderer失败:" << SDL_GetError() << endl; return; } SDL_Surface *image = IMG_Load("/Volumes/T5/CppPractice/renderer-dog/res/demo.jpg"); if (!image) { cout << "加载图片失败:" << SDL_GetError() << endl; return; } // 如果使用硬件加速,则必须将Surface转换成Texture SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, image); SDL_FreeSurface(image); SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, nullptr, nullptr); SDL_RenderPresent(renderer); SDL_Event windowEvent; while (true) { if (SDL_PollEvent(&windowEvent)) { if (windowEvent.type == SDL_QUIT) { std::cout << "终止程序" << std::endl; break; } } } SDL_DestroyRenderer(renderer); SDL_DestroyTexture(texture); SDL_DestroyWindow(window); SDL_Quit(); }
基本步骤
- 初始化
- 创建Window
- 创建Renderer,用于在Window上渲染内容
- 创建Surface,Surface其实就是像素的载体
- 如果需要使用硬件加速,需要将Surface转换成Texture
- 清除Renderer内容,并使用Renderer的Copy功能将texture内容复制到屏幕的指定区域
- 指定当前的Renderer.
- 事件监听
- 销毁各种对象
遇到的问题
- MacOS安装的SDL2_image库打开时提示安全提示
解决方案:
sudo spctl --master-disable
源码
- 作者:姜康
- 链接:https://jiangkang.tech/article/b92e830a-50fd-4698-ac38-de8dcd4422ee
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章