image.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. use std::{
  2. cell::{Cell, RefCell},
  3. sync::Arc,
  4. };
  5. use starry_client::base::{color::Color, renderer::Renderer};
  6. use crate::{
  7. base::{point::Point, rect::Rect},
  8. traits::place::Place,
  9. };
  10. use super::{HorizontalPlacement, VerticalPlacement, Widget};
  11. use crate::starry_server::base::image::Image as ImageAsset;
  12. pub struct Image {
  13. pub rect: Cell<Rect>,
  14. local_position: Cell<Point>,
  15. vertical_placement: Cell<VerticalPlacement>,
  16. horizontal_placement: Cell<HorizontalPlacement>,
  17. children: RefCell<Vec<Arc<dyn Widget>>>,
  18. /// 图像源数据
  19. pub image: RefCell<ImageAsset>,
  20. }
  21. impl Image {
  22. pub fn new(width: u32, height: u32) -> Arc<Self> {
  23. Self::from_image(ImageAsset::new(width as i32, height as i32))
  24. }
  25. pub fn from_color(width: u32, height: u32, color: Color) -> Arc<Self> {
  26. Self::from_image(ImageAsset::from_color(width as i32, height as i32, color))
  27. }
  28. pub fn from_image(image: ImageAsset) -> Arc<Self> {
  29. Arc::new(Image {
  30. rect: Cell::new(Rect::new(0, 0, image.width() as u32, image.height() as u32)),
  31. local_position: Cell::new(Point::new(0, 0)),
  32. vertical_placement: Cell::new(VerticalPlacement::Absolute),
  33. horizontal_placement: Cell::new(HorizontalPlacement::Absolute),
  34. children: RefCell::new(vec![]),
  35. image: RefCell::new(image),
  36. })
  37. }
  38. pub fn from_path(path: &[u8]) -> Option<Arc<Self>> {
  39. if let Some(image) = ImageAsset::from_path(path) {
  40. Some(Self::from_image(image))
  41. } else {
  42. None
  43. }
  44. }
  45. }
  46. impl Place for Image {}
  47. impl Widget for Image {
  48. fn name(&self) -> &str {
  49. "Image"
  50. }
  51. fn rect(&self) -> &Cell<Rect> {
  52. &self.rect
  53. }
  54. fn vertical_placement(&self) -> &Cell<VerticalPlacement> {
  55. &self.vertical_placement
  56. }
  57. fn horizontal_placement(&self) -> &Cell<HorizontalPlacement> {
  58. &self.horizontal_placement
  59. }
  60. fn local_position(&self) -> &Cell<Point> {
  61. &self.local_position
  62. }
  63. fn children(&self) -> &RefCell<Vec<Arc<dyn Widget>>> {
  64. &self.children
  65. }
  66. fn draw(&self, renderer: &mut dyn Renderer) {
  67. let rect = self.rect.get();
  68. let image = self.image.borrow();
  69. renderer.image(rect.x, rect.y, rect.width, rect.height, image.data());
  70. }
  71. }