How do I draw a pixel to a certain position? #361
Replies: 1 comment 2 replies
-
Hi! This is called pixel plotting and it's a very simple formula, basically structured like this: fn plot(buffer: &mut [u8], x: usize, y: usize, stride: usize, color: &[u8]) {
assert_eq!(color.len(), 4);
let i = x + y * stride * 4;
buffer[i..i + 4].copy_from_slice(color);
} Where Adjusting the function slightly allows it to be agnostic to the pixel format, but also allows misuse by passing fn plot(buffer: &mut [u8], x: usize, y: usize, stride: usize, color: &[u8]) {
let i = x + y * stride * color.len();
buffer[i..i + color.len()].copy_from_slice(color);
} The real problem with this is that it's very slow to call the function for one pixel at a time. A common optimization is called "blitting", which copies rows of pixels at a time. You can extend the second example above to do this, but it's easier to just use a crate that already has all of this worked out. I have had great success with This is a great primitive to build larger abstractions on, like sprites and even "flip book animations". |
Beta Was this translation helpful? Give feedback.
-
Hello! I'm using this library to show the results of my raytracer and haven't been able to wrap my head around how to set a value to the byte array. Say I have some (x,y) position and a colour (R,G,B). How can I translate the (x,y) coordinate to an index in the byte array?
Beta Was this translation helpful? Give feedback.
All reactions