![](/img/trans.png)
[英]how to draw a straight line in javafx that updates itself when the user moves the mouse?
[英]How to draw a rectangular which is moves by mouse click
任務如下: a) 繪制一個正方形,該正方形將根據鼠標的移動改變其大小和顏色 b) 使其每次單擊鼠標時,都會繪制一個具有相同大小和顏色參數的正方形鼠標的位置並凍結在適當的位置 c) 執行前面的操作,但應該已經點擊了幾下鼠標
我做了部分 a 並想出了部分 ba 一點點
void setup(){
size(500, 255);
}
int size = mouseX%100;
void draw(){
int size = mouseX%100;
background(50);
fill(255 - mouseY, 125 - mouseY, 175 - mouseY);
stroke(255);
rectMode(CENTER);
if ((mouseX >= 100) & (mouseX <= 199) | (mouseX >= 300) & (mouseX <= 399) | (mouseX >= 500) & (mouseX <= 599) ) {
size = 99;
size = size - mouseX%100;
}
rect(mouseX,mouseY,size,size);
if (mousePressed) {
int x = width - mouseX;
int y = height - mouseY;
rect(-x,-y,size,size);
}
}
我希望每次點擊,我都會在 window 中看到方塊。
創建一個 class 可以管理單個矩形並根據矩形的原點和輸入 position 更新矩形的大小:
final int MIN_SIZE = 5;
final int MAX_SIZE = 100;
class Rectangle {
int pos_x, pos_y, size;
color col;
Rectangle(int px, int py) {
col = color(0, 0, 255);
pos_x = px; pos_y = py;
size = MIN_SIZE;
}
void Update(int px, int py) {
size = max(abs(pos_x - px), abs(pos_y - py))*2;
size = max(MIN_SIZE, min(MAX_SIZE, size));
float w = float(size - MIN_SIZE) / float(MAX_SIZE - MIN_SIZE);
col = color(int(255*w), 0.0, int(255.0*(1.0-w)));
}
void Draw() {
fill(col);
rect(pos_x-size/2, pos_y-size/2, size, size);
}
}
創建一個矩形對象的變量列表( ArrayList
):
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
添加一個 state ( drawingRect
),它說明是否按下鼠標,並在鼠標事件回調 ( mousePressed()
、 mouseReleased()
) 中按下鼠標時添加一個新矩形:
void mousePressed() {
drawingRect = true;
rectangles.add(new Rectangle(mouseX, mouseY));
}
void mouseReleased() {
drawingRect = false;
}
如果按下鼠標並添加了一個矩形(由drawingRect
指示),則根據當前鼠標 position ( mouseX,
mouseY ). Draw all rectangles in a loop in
). Draw all rectangles in a loop in
:
void setup() {
size(600, 600);
}
void draw() {
if (drawingRect && rectangles.size() > 0) {
Rectangle lastRect = rectangles.get(rectangles.size()-1);
lastRect.Update(mouseX, mouseY);
}
background(255);
for (int i = 0; i < rectangles.size(); i++) {
Rectangle rect = rectangles.get(i);
rect.Draw();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.