【问题标题】:Adding Transparent Circle to background images将透明圆圈添加到背景图像
【发布时间】:2013-06-28 02:29:08
【问题描述】:

我需要制作鼓乐器。我已经有了背景图像和声音。现在我需要在鼓上添加 4 个透明圆圈来产生 4 种不同的声音。

import javax.swing.*;
import java.awt.event.*;

public class PictureOnClickOneSound 
{

  public static void main(String args[]) 
  {
    // Create a "clickable" image icon.
    ImageIcon icon = new ImageIcon("C:\\Users\\apr13mpsip\\Pictures\\Drum2.jpg");
    JLabel label = new JLabel(icon);
    label.addMouseListener(new MouseAdapter() 
    {
      public void mouseClicked(MouseEvent me) 
      {
        sound1.Sound1.play();
        System.out.println("CLICKED");
      }
    }); 

    // Add it to a frame.
    JFrame frame = new JFrame("My Window");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(label);
    frame.pack();
    frame.setVisible(true);
  }
}

【问题讨论】:

  • 如果圆圈是透明的,用户如何知道点击的位置?用户是否只是随机点击并希望获得最好的结果?您的图像是否有 4 个鼓,并且您试图覆盖每个鼓上的圆圈?
  • 是的,我的图像有 4 个鼓。我想把 4 圈放在 4 个鼓上
  • 1) 这与 Eclipse 无关(IE 在 Eclipse 中的操作方式与在 Netbeans 或 TextPad 中完全相同)2) 您应该编辑 your original post 而不是开始一个新的。
  • 顺便说一句 - 您可能会链接到(最好是小)图像,以便像this thread 中的人们可以进行实验。一幅画描绘一千个字。 ;)

标签: java image swing awt java-2d


【解决方案1】:

创建一个地图,其中包含一个表示图像上某个位置的形状以及单击该位置时播放的声音文件。比如:

Map<Shape, Sound> shapes = new Hashmap<Shape, Sound>();

shapes.put(new Ellipse2D.Double(0, 0, 50, 50), soundFile1);
shapes.put(new Ellipse2D.Double(50, 50, 50, 50), soundFile2);

然后在 mouseClicked() 事件中,您需要搜索地图以查看是否在您的任何形状中单击了鼠标。比如:

for (Shape shape: shapes.keySet())
{
    if (shape.contains(event.getPoint());
    {
        Sound sound = shapes.get(shape);
        sound.play();
    }
}

【讨论】:

  • 如果你不介意的话。你能告诉我把示例代码放在哪里吗
  • 我向您展示了哪些代码进入了鼠标侦听器。其他代码不会进入鼠标侦听器。代码不准确,因为我不知道您如何播放音乐。我向您展示的代码是一个概念,因为您还需要根据您的图像确定适当的形状位置。
【解决方案2】:

您不需要添加'透明圆圈',只需使用MouseEvent 的属性getX()getY() 来识别它在图像中被点击的位置,然后播放相对的声音。

对于每个圆,存储 x、y 中心位置和半径。

public class Circle{
   double xCenter;
   double yCenter;
   double radius;
}

当执行 MouseEvent 动作时,遍历圆圈并检查点击是否在任何范围内:

for(Circle c : circles){
   //check if the click was inside this circle
   if (Math.sqrt((c.xCenter-mouseEvent.getX())^2+(c.yCenter-mouseEvent.getY())^2) <= c.radius) {
      //play sound for c
   }
}

【讨论】:

  • 如果你不介意的话。您能告诉我根据我的代码在哪里插入您提供的示例吗?
  • 需要在mouseClicked方法中插入for循环,但需要根据图片中的x、y位置创建圆的实例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 2012-07-14
相关资源
最近更新 更多