缩放图像,同时使图像保持在SDL2中心

时间:2014-07-13 21:35:39

标签: c++ graphics 2d zoom sdl-2

我正在尝试使用此代码来缩放SDL2中的图像。我希望图像在缩放时保持居中,但我似乎无法弄清楚(我已经尝试了几种方法,到目前为止这个方法看起来最好......但这并不是很多)

void Image::drawFlat(SDL_Renderer* renderer, int x, int y, float scaleWidth, float scaleHeight) {
    if(this->position.x != x || this->position.y != y || this->scaleWidth != scaleWidth || this->scaleHeight != scaleHeight) {
        SDL_QueryTexture(this->imageCache, NULL, NULL, &this->position.w, &this->position.h);
        this->position.x = (int) x - (this->position.w * scaleWidth + this->position.w) / 2;
        this->position.y = (int) y - (this->position.h * scaleHeight + this->position.h) / 2;
        this->position.w = (int) this->position.w * scaleWidth;
        this->position.h = (int) this->position.h * scaleHeight;
        this->scaleWidth = scaleWidth;
        this->scaleHeight = scaleHeight;
        SDL_RenderCopy(renderer, this->imageCache, NULL, &this->position);
    }
}

1 个答案:

答案 0 :(得分:1)

你几乎就在那里。你只需要反转两个标志:

void Image::drawFlat(SDL_Renderer* renderer, int x, int y, float scaleWidth, float scaleHeight) {
    if(this->position.x != x || this->position.y != y || this->scaleWidth != scaleWidth || this->scaleHeight != scaleHeight) {
        SDL_QueryTexture(this->imageCache, NULL, NULL, &this->position.w, &this->position.h);
        this->position.x = (int) x - (this->position.w * scaleWidth - this->position.w) / 2;
        this->position.y = (int) y - (this->position.h * scaleHeight - this->position.h) / 2;
        this->position.w = (int) this->position.w * scaleWidth;
        this->position.h = (int) this->position.h * scaleHeight;
        this->scaleWidth = scaleWidth;
        this->scaleHeight = scaleHeight;
        SDL_RenderCopy(renderer, this->imageCache, NULL, &this->position);
    }
}

Online Demo(使用箭头移动,numpad +和 - 用于宽度缩放,[和]用于高度缩放)