Freeciv21
Develop your civilization from humble roots to a global empire
sprite.cpp
Go to the documentation of this file.
1 /*
2  Copyright (c) 1996-2023 Freeciv21 and Freeciv contributors. This file is
3  part of Freeciv21. Freeciv21 is free software: you can redistribute it
4  and/or modify it under the terms of the GNU General Public License as
5  published by the Free Software Foundation, either version 3 of the
6  License, or (at your option) any later version. You should have received
7  a copy of the GNU General Public License along with Freeciv21. If not,
8  see https://www.gnu.org/licenses/.
9  */
10 
11 // Qt
12 #include <QImageReader>
13 #include <QPainter>
14 // utility
15 #include "log.h"
16 // client
17 #include "fc_client.h"
18 #include "sprite.h"
19 
25 QPixmap *load_gfxfile(const char *filename)
26 {
27  QPixmap *entire = new QPixmap;
28 
29  if (QPixmapCache::find(QString(filename), entire)) {
30  return entire;
31  }
32  entire->load(QString(filename));
33  QPixmapCache::insert(QString(filename), *entire);
34 
35  return entire;
36 }
37 
59 QPixmap *crop_sprite(const QPixmap *source, int x, int y, int width,
60  int height, const QPixmap *mask, int mask_offset_x,
61  int mask_offset_y)
62 {
63  QPainter p;
64  QRectF source_rect;
65  QRectF dest_rect;
66  QPixmap *cropped;
67 
68  fc_assert_ret_val(source, nullptr);
69 
70  if (!width || !height) {
71  return nullptr;
72  }
73  cropped = new QPixmap(width, height);
74  cropped->fill(Qt::transparent);
75  source_rect = QRectF(x, y, width, height);
76  dest_rect = QRectF(0, 0, width, height);
77 
78  p.begin(cropped);
79  p.setRenderHint(QPainter::Antialiasing);
80  p.drawPixmap(dest_rect, *source, source_rect);
81  p.end();
82 
83  if (mask) {
84  int mw = mask->width();
85  int mh = mask->height();
86 
87  source_rect = QRectF(0, 0, mw, mh);
88  dest_rect = QRectF(mask_offset_x - x, mask_offset_y - y, mw, mh);
89  p.begin(cropped);
90  p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
91  p.setRenderHint(QPainter::Antialiasing);
92  p.setRenderHint(QPainter::SmoothPixmapTransform);
93  p.drawPixmap(dest_rect, *mask, source_rect);
94  p.end();
95  }
96 
97  return cropped;
98 }
#define fc_assert_ret_val(condition, val)
Definition: log.h:114
QPixmap * crop_sprite(const QPixmap *source, int x, int y, int width, int height, const QPixmap *mask, int mask_offset_x, int mask_offset_y)
Create a new sprite by cropping and taking only the given portion of the image.
Definition: sprite.cpp:59
QPixmap * load_gfxfile(const char *filename)
Load the given graphics file into a sprite.
Definition: sprite.cpp:25