| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- using Godot;
- using System;
- public partial class EditorTest : Control
- {
- [Export] private TextureRect _textureRect;
- [Export] private Panel _dropArea;
-
- // Called when the node enters the scene tree for the first time.
- public override void _Ready()
- {
- // 允许接收拖拽
- MouseFilter = MouseFilterEnum.Pass;
-
- // 连接信号
- _dropArea.GuiInput += OnDropAreaGuiInput;
-
- // 设置拖拽区域属性
- _dropArea.MouseFilter = MouseFilterEnum.Pass;
- _dropArea.SizeFlagsHorizontal = SizeFlags.ExpandFill;
- _dropArea.SizeFlagsVertical = SizeFlags.ExpandFill;
-
- }
- // Called every frame. 'delta' is the elapsed time since the previous frame.
- public override void _Process(double delta)
- {
- }
-
-
- public override bool _CanDropData(Vector2 at, Variant data)
- {
- // 检查拖拽的数据是否为文件路径
- if (data.VariantType == Variant.Type.String)
- {
- string filePath = data.AsString();
- return filePath.ToLower().EndsWith(".png");
- }
- return false;
- }
-
- public override void _DropData(Vector2 at, Variant data)
- {
- string filePath = data.AsString();
- LoadAndDisplayImage(filePath);
- }
-
- private void OnDropAreaGuiInput(InputEvent @event)
- {
- if (@event is InputEventMouseButton mouseEvent &&
- mouseEvent.Pressed &&
- mouseEvent.ButtonIndex == MouseButton.Left)
- {
- // 可以处理点击事件(可选)
- }
- }
-
- private void LoadAndDisplayImage(string filePath)
- {
- try
- {
- // 加载图片
- Image image = new Image();
- Error error = image.Load(filePath);
-
- if (error == Error.Ok)
- {
- // 创建纹理
- ImageTexture texture = ImageTexture.CreateFromImage(image);
-
- // 显示在TextureRect中
- if (_textureRect != null)
- {
- _textureRect.Texture = texture;
- GD.Print($"成功加载图片: {filePath}");
- }
- }
- else
- {
- GD.PrintErr($"加载图片失败: {error}");
- }
- }
- catch (Exception ex)
- {
- GD.PrintErr($"加载图片时出错: {ex.Message}");
- }
- }
-
- // 可选:添加一些视觉效果
- public override void _Notification(int what)
- {
- base._Notification(what);
-
- if (what == NotificationDragBegin)
- {
- // 拖拽开始时的效果
- Modulate = new Color(1, 1, 1, 0.5f);
- }
- else if (what == NotificationDragEnd)
- {
- // 拖拽结束时的效果
- Modulate = new Color(1, 1, 1, 1);
- }
- }
- }
|