Skip to content

Commit 0646cc1

Browse files
feat(cli): support non-square source images in tauri icon (#15620)
* feat(cli): support non-square source images in `tauri icon` `tauri icon` rejected any source whose width and height differ. Add a `--fit` option, modeled on the CSS `object-fit` property, to square a non-square source before generating icons: - `cover`: scale to fill the square, center-cropping the longer side - `contain`: scale to fit inside the square, padding the shorter side with transparency SVG sources are rasterized at their native size before fitting. Non-square sources without `--fit` still error, now with a hint pointing to the flag. closes #15376 * fix(cli): rasterize small SVG sources at a higher resolution * refactor(cli): apply icon --fit as SVG render transform Keep SVG sources as a vector tree through the fit step and apply the crop/pad as a transform when rendering each target size, instead of rasterizing once at a fixed floor and squaring the bitmap. Icons are now rendered directly from the vector at their final resolution, so a source with a small intrinsic size stays crisp and the MIN_SVG_RASTER_SIZE upscale hack is gone. * Small refactor * Inline width and height fn * Clean up comments * use `::min` `::max` * Add `@tauri-apps/cli` * Update tests --------- Co-authored-by: Tony <68118705+Legend-Master@users.noreply.github.com> Co-authored-by: Tony <legendmastertony@gmail.com>
1 parent af465ea commit 0646cc1

2 files changed

Lines changed: 193 additions & 36 deletions

File tree

‎.changes/icon-non-square-fit.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"tauri-cli": "minor:feat"
3+
"@tauri-apps/cli": "minor:feat"
4+
---
5+
6+
Add a `--fit` option to `tauri icon` to accept non-square source images. `--fit cover` center-crops the source to a square (clipping the longer side) and `--fit contain` pads the shorter side with transparency. Non-square sources without `--fit` keep erroring, now with a hint pointing to the flag.

‎crates/tauri-cli/src/icon.rs‎

Lines changed: 187 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use std::{
1616
sync::Arc,
1717
};
1818

19-
use clap::Parser;
19+
use clap::{Parser, ValueEnum};
2020
use icns::{IconFamily, IconType};
2121
use image::{
2222
codecs::{
@@ -99,48 +99,38 @@ pub struct Options {
9999
/// The background color of the iOS icon - string as defined in the W3C's CSS Color Module Level 4 <https://www.w3.org/TR/css-color-4/>.
100100
#[clap(long, default_value = "#fff")]
101101
ios_color: String,
102+
103+
/// How to fit a non-square source image into the square icon canvas, similar to the CSS `object-fit` property.
104+
///
105+
/// When not set, a non-square source is rejected.
106+
#[clap(long, value_enum)]
107+
fit: Option<Fit>,
108+
}
109+
110+
/// How to fit a non-square source image into the square icon canvas.
111+
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
112+
enum Fit {
113+
/// Scale the source to fill the square, center-cropping the longer side (may clip content).
114+
Cover,
115+
/// Scale the source to fit inside the square, padding the shorter side with transparency.
116+
Contain,
102117
}
103118

104119
#[derive(Clone)]
105120
#[allow(clippy::large_enum_variant)]
106121
enum Source {
107-
Svg(resvg::usvg::Tree),
122+
Svg {
123+
tree: resvg::usvg::Tree,
124+
/// Records how a non-square source should be squared
125+
fit: Option<Fit>,
126+
},
108127
DynamicImage(DynamicImage),
109128
}
110129

111130
impl Source {
112-
fn width(&self) -> u32 {
113-
match self {
114-
Self::Svg(svg) => svg.size().width() as u32,
115-
Self::DynamicImage(i) => i.width(),
116-
}
117-
}
118-
119-
fn height(&self) -> u32 {
120-
match self {
121-
Self::Svg(svg) => svg.size().height() as u32,
122-
Self::DynamicImage(i) => i.height(),
123-
}
124-
}
125-
126131
fn resize_exact(&self, size: u32) -> DynamicImage {
127132
match self {
128-
Self::Svg(svg) => {
129-
let mut pixmap = tiny_skia::Pixmap::new(size, size).unwrap();
130-
let scale = size as f32 / svg.size().height();
131-
resvg::render(
132-
svg,
133-
tiny_skia::Transform::from_scale(scale, scale),
134-
&mut pixmap.as_mut(),
135-
);
136-
// Switch to use `Pixmap::take_demultiplied` in the future when it's published
137-
// https://github.com/linebender/tiny-skia/blob/624257c0feb394bf6c4d0d688f8ea8030aae320f/src/pixmap.rs#L266
138-
let img_buffer = ImageBuffer::from_par_fn(size, size, |x, y| {
139-
let pixel = pixmap.pixel(x, y).unwrap().demultiply();
140-
Rgba([pixel.red(), pixel.green(), pixel.blue(), pixel.alpha()])
141-
});
142-
DynamicImage::ImageRgba8(img_buffer)
143-
}
133+
Self::Svg { tree, fit } => rasterize_svg(tree, *fit, size),
144134
Self::DynamicImage(image) => {
145135
// image.resize_exact(size, size, FilterType::Lanczos3)
146136
resize_image(image, size, size)
@@ -196,7 +186,10 @@ fn read_source(path: PathBuf) -> Result<Source> {
196186
usvg::Tree::from_data(&svg_data, &opt).unwrap()
197187
};
198188

199-
Ok(Source::Svg(rtree))
189+
Ok(Source::Svg {
190+
tree: rtree,
191+
fit: None,
192+
})
200193
} else {
201194
Ok(Source::DynamicImage(DynamicImage::ImageRgba8(
202195
open(&path)
@@ -232,6 +225,84 @@ fn parse_bg_color(bg_color_string: &String) -> Result<Rgba<u8>> {
232225
Ok(bg_color)
233226
}
234227

228+
// Rasterize an SVG tree to a square `size`x`size` `DynamicImage`, applying the
229+
// `fit` mode as a render transform. Because the vector tree is rendered at the
230+
// final resolution, there is no intermediate bitmap and no quality loss — a
231+
// source declaring a tiny intrinsic size (e.g. `width="16"`) is just as crisp
232+
// as a large one.
233+
fn rasterize_svg(tree: &usvg::Tree, fit: Option<Fit>, size: u32) -> DynamicImage {
234+
let native = tree.size();
235+
let (nw, nh) = (native.width(), native.height());
236+
237+
// `side` is the square edge (in user units) we crop/pad the source to; the
238+
// offsets recenter the content within that square.
239+
let (side, off_x, off_y) = match fit {
240+
// Crop to the shorter side, centered.
241+
Some(Fit::Cover) => {
242+
let side = f32::min(nw, nh);
243+
(side, (nw - side) / 2.0, (nh - side) / 2.0)
244+
}
245+
// Pad the shorter side, centered (offsets are negative → transparent bands).
246+
Some(Fit::Contain) => {
247+
let side = f32::max(nw, nh);
248+
(side, (nw - side) / 2.0, (nh - side) / 2.0)
249+
}
250+
// Already square (or squaring not requested): scale to fit as-is.
251+
None => (nh, 0.0, 0.0),
252+
};
253+
254+
let scale = size as f32 / side;
255+
let transform =
256+
tiny_skia::Transform::from_scale(scale, scale).post_translate(-off_x * scale, -off_y * scale);
257+
258+
let mut pixmap = tiny_skia::Pixmap::new(size, size).unwrap();
259+
resvg::render(tree, transform, &mut pixmap.as_mut());
260+
261+
// Switch to use `Pixmap::take_demultiplied` in the future when it's published
262+
// https://github.com/linebender/tiny-skia/blob/624257c0feb394bf6c4d0d688f8ea8030aae320f/src/pixmap.rs#L266
263+
let img_buffer = ImageBuffer::from_par_fn(size, size, |x, y| {
264+
let pixel = pixmap.pixel(x, y).unwrap().demultiply();
265+
Rgba([pixel.red(), pixel.green(), pixel.blue(), pixel.alpha()])
266+
});
267+
DynamicImage::ImageRgba8(img_buffer)
268+
}
269+
270+
// Convert a non-square source into a square one according to the `fit` mode.
271+
// SVG sources stay vector — the fit is recorded and applied at render time; only
272+
// raster sources are cropped/padded here.
273+
fn fit_to_square(source: Source, fit: Fit) -> Source {
274+
let image = match source {
275+
Source::DynamicImage(image) => image,
276+
Source::Svg { tree, .. } => {
277+
return Source::Svg {
278+
tree,
279+
fit: Some(fit),
280+
}
281+
}
282+
};
283+
284+
let (width, height) = image.dimensions();
285+
let squared = match fit {
286+
Fit::Cover => {
287+
let side = u32::min(width, height);
288+
image.crop_imm((width - side) / 2, (height - side) / 2, side, side)
289+
}
290+
Fit::Contain => {
291+
let side = u32::max(width, height);
292+
let mut canvas = ImageBuffer::from_pixel(side, side, Rgba([0, 0, 0, 0]));
293+
image::imageops::overlay(
294+
&mut canvas,
295+
&image,
296+
((side - width) / 2) as i64,
297+
((side - height) / 2) as i64,
298+
);
299+
DynamicImage::ImageRgba8(canvas)
300+
}
301+
};
302+
303+
Source::DynamicImage(squared)
304+
}
305+
235306
pub fn command(options: Options) -> Result<()> {
236307
let input = options.input;
237308
let out_dir = options.output.unwrap_or_else(|| {
@@ -263,10 +334,21 @@ pub fn command(options: Options) -> Result<()> {
263334
None => input.clone(),
264335
};
265336

266-
let source = read_source(default_icon)?;
337+
let mut source = read_source(default_icon)?;
267338

268-
if source.height() != source.width() {
269-
crate::error::bail!("Source image must be square");
339+
let (width, height) = match &source {
340+
Source::Svg { tree, .. } => (tree.size().width() as u32, tree.size().height() as u32),
341+
Source::DynamicImage(i) => (i.width(), i.height()),
342+
};
343+
if width != height {
344+
if let Some(fit) = options.fit {
345+
log::info!(action = "Fit"; "Squaring {width}x{height} source with `{fit:?}`");
346+
source = fit_to_square(source, fit);
347+
} else {
348+
crate::error::bail!(
349+
"Source image must be square; pass `--fit cover` or `--fit contain` to convert a non-square source"
350+
)
351+
}
270352
}
271353

272354
if png_icon_sizes.is_empty() {
@@ -982,3 +1064,72 @@ fn apply_round_mask(
9821064

9831065
DynamicImage::ImageRgba8(out)
9841066
}
1067+
1068+
#[cfg(test)]
1069+
mod tests {
1070+
use super::*;
1071+
1072+
fn landscape(width: u32, height: u32) -> Source {
1073+
// opaque red rectangle
1074+
Source::DynamicImage(DynamicImage::ImageRgba8(ImageBuffer::from_pixel(
1075+
width,
1076+
height,
1077+
Rgba([255, 0, 0, 255]),
1078+
)))
1079+
}
1080+
1081+
fn svg_landscape() -> usvg::Tree {
1082+
// 40x20 opaque red rectangle
1083+
let data = br#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><rect width="40" height="20" fill="red"/></svg>"#;
1084+
usvg::Tree::from_data(data, &usvg::Options::default()).unwrap()
1085+
}
1086+
1087+
#[test]
1088+
fn cover_center_crops_to_square() {
1089+
let out = fit_to_square(landscape(40, 20), Fit::Cover);
1090+
let Source::DynamicImage(image) = out else {
1091+
panic!("expected a raster source");
1092+
};
1093+
assert_eq!((image.width(), image.height()), (20, 20));
1094+
// the cropped region keeps the original content (fully opaque)
1095+
assert_eq!(image.get_pixel(10, 10)[3], 255);
1096+
}
1097+
1098+
#[test]
1099+
fn contain_pads_shorter_side_with_transparency() {
1100+
let out = fit_to_square(landscape(40, 20), Fit::Contain);
1101+
let Source::DynamicImage(image) = out else {
1102+
panic!("expected a raster source");
1103+
};
1104+
assert_eq!((image.width(), image.height()), (40, 40));
1105+
// top padding band is transparent, the centered content is opaque
1106+
assert_eq!(image.get_pixel(20, 0)[3], 0);
1107+
assert_eq!(image.get_pixel(20, 20)[3], 255);
1108+
}
1109+
1110+
#[test]
1111+
fn svg_cover_renders_square_from_vector() {
1112+
let source = Source::Svg {
1113+
tree: svg_landscape(),
1114+
fit: Some(Fit::Cover),
1115+
};
1116+
// rendered directly from the vector tree at the requested size
1117+
let image = source.resize_exact(64);
1118+
assert_eq!((image.width(), image.height()), (64, 64));
1119+
// center of the cropped region stays opaque
1120+
assert_eq!(image.get_pixel(32, 32)[3], 255);
1121+
}
1122+
1123+
#[test]
1124+
fn svg_contain_pads_shorter_side_with_transparency() {
1125+
let source = Source::Svg {
1126+
tree: svg_landscape(),
1127+
fit: Some(Fit::Contain),
1128+
};
1129+
let image = source.resize_exact(64);
1130+
assert_eq!((image.width(), image.height()), (64, 64));
1131+
// top band is transparent padding, the centered content is opaque
1132+
assert_eq!(image.get_pixel(32, 2)[3], 0);
1133+
assert_eq!(image.get_pixel(32, 32)[3], 255);
1134+
}
1135+
}

0 commit comments

Comments
 (0)