代码之家  ›  专栏  ›  技术社区  ›  NeoSanguine

SDL2只绘制整个纹理,而不是像我编码的那样绘制纹理的一部分

  •  -1
  • NeoSanguine  · 技术社区  · 12 年前

    由于某种奇怪的原因,每当我试图将一个较大的图像文件分割成(在我的情况下)32x32的图片时,我得到的却是整个图片,看起来被压缩成32x32(整个图片)。尽管在玩转了这些值之后,我意识到由于某种原因,SDL完全忽略了我使用SDL_Rect源(src)的请求。 这意味着当我运行程序时,我将源(src)矩形更改为的每个值都不会改变实际图像(甚至是一个荒谬的值)。

    雪碧.h

    #ifndef SPRITE_H_
    #define SPRITE_H_
    
    #pragma once
    #include "Game.h"
    
    struct Game;
    
    struct Sprite
    {
        //Needs to be fixed :/
        //Sprite(const std::string& filepath,int x,int y,int width, int height,Game*game);
        Sprite();
        ~Sprite();
        void Load(const std::string& filepath, int x, int y,int width,int height, Game*game);
        void Draw(Game*game);
        SDL_Rect*getDstRect(){ return &dst; }
        SDL_Rect*getSrcRect(){ return &src; }
    
    private:
        SDL_Surface*surface = NULL;
        SDL_Texture*texture = NULL;
        SDL_Rect src;
        SDL_Rect dst;
        int img_width;
        int img_height;
    
    };
    
    #endif // SPRITE_H_
    

    精灵.cpp

    #include "Sprite.h"
    
    Sprite::Sprite()
    {
    
    }
    
    Sprite::~Sprite()
    {
    
        SDL_DestroyTexture(texture);
    
    
        surface = NULL;
        texture = NULL;
    }
    
    void Sprite::Load(const std::string& filepath, int x, int y, int width, int height, Game*game)
    {
        bool success = true;
        surface = IMG_Load(filepath.c_str());
        if (surface == NULL)
        {
            game->getConsole()->Error("SPRITE::Surface Is Not Loaded");
            success = false;
        }
        else
            game->getConsole()->Text("SPRITE::Surface Is Loaded");
    
    
    
        texture = SDL_CreateTextureFromSurface(game->getRenderer(), surface);
        if (texture == NULL)
        {
            game->getConsole()->Error("SPRITE::Texture Is Not Loaded");
            success = false;
        }
        else
            game->getConsole()->Text("SPRITE::Texture is Loaded");
    
    
    
        dst.x = x;
        dst.y = y;
        dst.w = height;
        dst.h = height;
    
    
        src.x = 0;
        src.y = 0;
        src.w = 0;
        src.h = 0;
    
        SDL_QueryTexture(texture, NULL, NULL, &src.w, &src.h);
    
        SDL_FreeSurface(surface);
    
        if (success)
            game->getConsole()->Text("Loaded Sprite at " + filepath);
        else
            game->getConsole()->Error("SPRITE::Failed To Load Sprite at " + filepath);
    
    }
    
    void Sprite::Draw(Game*game)
    {
        SDL_RenderCopy(game->getRenderer(), texture, &src,&dst);
    }
    

    地图类的一部分

    testPlayer.Load("bin/sprites/player.png", 200,200,32,32, game);
    

    这就是我试图在干扰源(src)矩形之后更改目标(dst)矩形的值的地方。

    1 回复  |  直到 12 年前
        1
  •  2
  •   keltar    12 年前

    https://wiki.libsdl.org/SDL_RenderCopy

    数据导向器 -目标SDL_Rect结构或整个渲染目标的NULL。 纹理将被拉伸 以填充给定的矩形。

    短版本-调整源矩形,使其宽度和高度与目标矩形相同,并调整{x,y},使其具有要提取的片段的起始位置。