psemek/libs/ui_legacy/source/image_view.cpp

91 lines
1.7 KiB
C++

#include <psemek/ui/image_view.hpp>
namespace psemek::ui
{
void image_view::set_upscale(bool value)
{
upscale_ = value;
post_reshape();
}
void image_view::set_downscale(bool value)
{
downscale_ = value;
post_reshape();
}
void image_view::set_keep_aspect_ratio(bool value)
{
keep_aspect_ratio_ = value;
post_reshape();
}
void image_view::set_image(gfx::texture_view_2d image)
{
image_ = image;
post_reshape();
}
math::box<float, 2> image_view::size_constraints() const
{
auto r = element::size_constraints();
auto st = merged_own_style();
if (image_)
{
auto const size = math::cast<int>(image_.size()) * *st->scale;
if (!downscale_)
{
r[0].min = size[0];
r[1].min = size[1];
}
if (!upscale_)
{
r[0].max = size[0];
r[1].max = size[1];
}
}
return r;
}
void image_view::draw(painter & p) const
{
if (!image_) return;
auto st = merged_own_style();
auto const size = math::cast<int>(image_.size()) * *st->scale;
auto box = shape_.box;
if (!upscale_)
{
if (size[0] < box[0].length())
box[0] = math::shrink(box[0], (box[0].length() - size[0]) / 2.f);
if (size[1] < box[1].length())
box[1] = math::shrink(box[1], (box[1].length() - size[1]) / 2.f);
}
if (keep_aspect_ratio_ && size[0] > 0.f && size[1] > 0.f)
{
if (size[0] * box[1].length() < box[0].length() * size[1])
{
float const width = box[1].length() * size[0] / size[1];
box[0] = math::shrink(box[0], (box[0].length() - width) / 2.f);
}
else
{
float const height = box[0].length() * size[1] / size[0];
box[1] = math::shrink(box[1], (box[1].length() - height) / 2.f);
}
}
p.draw_image(box, image_, {color_});
}
}