EditorTest.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using Godot;
  2. using System;
  3. public partial class EditorTest : Control
  4. {
  5. [Export] private TextureRect _textureRect;
  6. [Export] private Panel _dropArea;
  7. // Called when the node enters the scene tree for the first time.
  8. public override void _Ready()
  9. {
  10. // 允许接收拖拽
  11. MouseFilter = MouseFilterEnum.Pass;
  12. // 连接信号
  13. _dropArea.GuiInput += OnDropAreaGuiInput;
  14. // 设置拖拽区域属性
  15. _dropArea.MouseFilter = MouseFilterEnum.Pass;
  16. _dropArea.SizeFlagsHorizontal = SizeFlags.ExpandFill;
  17. _dropArea.SizeFlagsVertical = SizeFlags.ExpandFill;
  18. }
  19. // Called every frame. 'delta' is the elapsed time since the previous frame.
  20. public override void _Process(double delta)
  21. {
  22. }
  23. public override bool _CanDropData(Vector2 at, Variant data)
  24. {
  25. // 检查拖拽的数据是否为文件路径
  26. if (data.VariantType == Variant.Type.String)
  27. {
  28. string filePath = data.AsString();
  29. return filePath.ToLower().EndsWith(".png");
  30. }
  31. return false;
  32. }
  33. public override void _DropData(Vector2 at, Variant data)
  34. {
  35. string filePath = data.AsString();
  36. LoadAndDisplayImage(filePath);
  37. }
  38. private void OnDropAreaGuiInput(InputEvent @event)
  39. {
  40. if (@event is InputEventMouseButton mouseEvent &&
  41. mouseEvent.Pressed &&
  42. mouseEvent.ButtonIndex == MouseButton.Left)
  43. {
  44. // 可以处理点击事件(可选)
  45. }
  46. }
  47. private void LoadAndDisplayImage(string filePath)
  48. {
  49. try
  50. {
  51. // 加载图片
  52. Image image = new Image();
  53. Error error = image.Load(filePath);
  54. if (error == Error.Ok)
  55. {
  56. // 创建纹理
  57. ImageTexture texture = ImageTexture.CreateFromImage(image);
  58. // 显示在TextureRect中
  59. if (_textureRect != null)
  60. {
  61. _textureRect.Texture = texture;
  62. GD.Print($"成功加载图片: {filePath}");
  63. }
  64. }
  65. else
  66. {
  67. GD.PrintErr($"加载图片失败: {error}");
  68. }
  69. }
  70. catch (Exception ex)
  71. {
  72. GD.PrintErr($"加载图片时出错: {ex.Message}");
  73. }
  74. }
  75. // 可选:添加一些视觉效果
  76. public override void _Notification(int what)
  77. {
  78. base._Notification(what);
  79. if (what == NotificationDragBegin)
  80. {
  81. // 拖拽开始时的效果
  82. Modulate = new Color(1, 1, 1, 0.5f);
  83. }
  84. else if (what == NotificationDragEnd)
  85. {
  86. // 拖拽结束时的效果
  87. Modulate = new Color(1, 1, 1, 1);
  88. }
  89. }
  90. }