File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ use macroquad:: prelude:: * ;
2+
3+ #[ macroquad:: main( "Upscaling" ) ]
4+ async fn main ( ) {
5+ let texture: Texture2D = load_texture ( "examples/rustacean_happy.png" ) . await . unwrap ( ) ;
6+ let double = Texture2D :: from_image ( & texture. get_texture_data ( ) . upscale ( 2 ) ) ;
7+ let triple = Texture2D :: from_image ( & texture. get_texture_data ( ) . upscale ( 3 ) ) ;
8+
9+ loop {
10+ clear_background ( LIGHTGRAY ) ;
11+ draw_texture ( & texture, 40. , 40. , WHITE ) ;
12+ draw_texture ( & double, 140. , 140. , WHITE ) ;
13+ draw_texture ( & triple, 240. , 240. , WHITE ) ;
14+
15+ next_frame ( ) . await
16+ }
17+ }
Original file line number Diff line number Diff line change @@ -323,6 +323,38 @@ impl Image {
323323 )
324324 . unwrap ( ) ;
325325 }
326+
327+ /// Scales an image up by the given factor `n`.
328+ /// Returns the new image.
329+ pub fn upscale ( & self , n : u16 ) -> Self {
330+ let mut new_bytes = vec ! [ ] ;
331+ let mut current_line_length = 0 ;
332+
333+ for pixel in self . get_image_data ( ) {
334+ // repeat n times horizontally
335+ for _ in 0 ..n {
336+ new_bytes. extend_from_slice ( pixel) ;
337+ }
338+ current_line_length += 1 ;
339+
340+ if current_line_length == self . width {
341+ // repeat n - 1 times vertically, because one line already exists
342+ let last_line = new_bytes
343+ [ ( new_bytes. len ( ) - ( 4 * self . width ( ) * n as usize ) ) ..new_bytes. len ( ) ]
344+ . to_vec ( ) ;
345+ for _ in 0 ..n - 1 {
346+ new_bytes. extend_from_slice ( & last_line) ;
347+ }
348+ current_line_length = 0 ;
349+ }
350+ }
351+
352+ Self {
353+ width : self . width * n,
354+ height : self . height * n,
355+ bytes : new_bytes,
356+ }
357+ }
326358}
327359
328360/// Loads an [Image] from a file into CPU memory.
You can’t perform that action at this time.
0 commit comments