image.rs 2.3 KB

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