我正在尝试使用此代码来缩放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);
}
}
答案 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 +和 - 用于宽度缩放,[和]用于高度缩放)