How to add a function to dropdown list? - processing

I've added a drop down list in processing using controlp5 library. I want to transmit data serially to Arduino when certain item is selected in the list. How to add the control for this purpose?
Here's my code:
void setup{
d1 = cp5.addDropdownList("color")
.setPosition(((width/4)-50), ((height/2)-40))
.setBackgroundColor(color(37, 126, 214))
.setFont(font1)
.setItemHeight(25)
.setBarHeight(20)
.addItem("red ", d1)
.addItem("blue ", d1)
.addItem("green ", d1)
}
I want to send a character 'r','b','g' to Arduino when each item is selected respectively. Suggest me how to write the code for my purpose.

Dropdown list is deprecated as the author says in the example, I think the simplest way is to implement ScrollableList, which is more flexible, and send the data though Serial Port to Arduino.
// Import java utils, for the list to add to the scrollable list
import java.util.*;
// Import ControlP5 library and declare it
import controlP5.*;
ControlP5 cp5;
// Import the Serial port and declare it
import processing.serial.*;
Serial myPort; // Create object from Serial class
void setup() {
size(400, 400);
// Initialize the Serial port
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);-
// Initialize the dropdown list
cp5 = new ControlP5(this);
List l = Arrays.asList("red", "green", "blue");
/* add a ScrollableList, by default it behaves like a DropdownList */
cp5.addScrollableList("dropdown")
.setPosition(100, 100)
.setSize(200, 100)
.setBarHeight(20)
.setItemHeight(20)
.addItems(l)
;
}
void draw() {
background(255);
}
// Dropdown callback function fromthe ScrollableList, triggered when you select an item
void dropdown(int n) {
/* request the selected item based on index n and store in a char */
String string = cp5.get(ScrollableList.class, "dropdown").getItem(n).get("name").toString();
char c = string.charAt(0);
// Write the char to the serial port
myPort.write(c);
}
On the Arduino side
char val; // Data received from the serial port
void setup() {
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
while (Serial.available()) { // If data is available to read,
val = Serial.read(); // read it and store it in val
}
}

Related

How to display microbit's orientation as a 3d model in processing?

I am working on a project with my rocketry club.
I want to have a microbit control the orientation of the fins to auto-stabilize the rocket.
But first, I tried to make a processing code to display in real-time my micro-bit's orientation using its integrated gyroscope.
Here's my processing code :
import processing.serial.*; // import the serial library
Serial myPort; // create a serial object
float xRot = 0; // variables to store the rotation angles
float yRot = 0;
float zRot = 0;
String occ[];
void setup() {
size(400, 400, P3D); // set the size of the window and enable 3D rendering
String portName = Serial.list()[0]; // get the name of the first serial port
myPort = new Serial(this, portName, 115200); // open a connection to the serial port
println((Object[]) Serial.list());
}
void draw() {
background(255); // clear the screen
translate(width/2, height/2, 0); // center the cube on the screen
rotateX(xRot); // apply the rotations
rotateZ(yRot);
rotateY(zRot);
fill(200); // set the fill color
box(100); // draw the cube
}
void serialEvent(Serial myPort) {
// this function is called whenever new data is available
// read the incoming data from the serial port
String data = myPort.readStringUntil('\n'); // read the data as a string
// print the incoming data to the console if it is not an empty string
if (data != null) {
println(data);
}
delay(10);
if (data != null) {
// split the string into separate values
String[] values = split(data, ',');
// convert the values to floats and store them in the rotation variables
xRot = radians(float(values[0]));
yRot = radians(float(values[1]));
zRot = radians(float(values[2]));
}
}
and here's the python code I have on my microbit
pitch = 0
roll = 0
x = 0
y = 0
z = 0
def on_forever():
global pitch, roll, x, y, z
pitch = input.rotation(Rotation.PITCH) + 90
roll = input.rotation(Rotation.ROLL) + 90
servos.P2.set_angle(pitch)
servos.P1.set_angle(roll)
x = input.rotation(Rotation.PITCH)
y = input.rotation(Rotation.ROLL)
z = 1
serial.set_baud_rate(BaudRate.BAUD_RATE115200)
serial.write_string(str(x) + "," + str(y) + "," + str(z) + "\n")
basic.forever(on_forever)
What happens when I run my code is that a cube appears and rotates weirdly for a short time, then, the cube stops and processing prints "Error, disabling serialEvent() for COM5 null".
Please help me out, I really need this code to be working!
Is this the documentation for the micro:bit Python API you're using ?
input.rotation (as the reference mentions), returns accelerometer data:
a number that means how much the micro:bit is tilted in the direction you ask for. This is a value in degrees between -180 to 180 in either the Rotation.Pitch or the Rotation.Roll direction of rotation.
I'd start with a try/catch block to get more details on the actual error.
e.g. is it the actual serial communication (e.g. resetting the baud rate over and over again (serial.set_baud_rate(BaudRate.BAUD_RATE115200)) instead of once) or optimistically assuming there will be 0 errors in serial communication and the string will always split to at least 3 values.
Unfortunately I won't have the resources to test with an actual device, so the following code might contain errors, but hopefully it illustrates some of the ideas.
I'd try simplifying/minimising the amount of data used on the micropython (and setting the baud rate once) and removing the need to read accelerometer data twice in the same iteration. If z is always 1 it can probably be ignored (you always rotate by 1 degree in Processing if necessary):
pitch = 0
roll = 0
x = 0
y = 0
def on_forever():
global pitch, roll, x, y
x = input.rotation(Rotation.PITCH)
y = input.rotation(Rotation.ROLL)
pitch = x + 90
roll = y + 90
servos.P2.set_angle(pitch)
servos.P1.set_angle(roll)
serial.write_string(str(x) + "," + str(y) + "\n")
serial.set_baud_rate(BaudRate.BAUD_RATE115200)
basic.forever(on_forever)
On the processing side, I'd surround serial code with try/catch just in case anything went wrong and double check every step of the string parsing process:
import processing.serial.*; // import the serial library
Serial myPort; // create a serial object
float xRot = 0; // variables to store the rotation angles
float yRot = 0;
void setup() {
size(400, 400, P3D); // set the size of the window and enable 3D rendering
String portNames = Serial.list();
println(portNames);
String portName = portNames[0]; // get the name of the first serial port
try {
myPort = new Serial(this, portName, 115200); // open a connection to the serial port
myPort.bufferUntil('\n');
} catch (Exception e){
println("error opening serial port " + portName + "\ndouble check USB is connected and the port isn't already open in another app")
e.printStackTrace();
}
}
void draw() {
background(255); // clear the screen
translate(width/2, height/2, 0); // center the cube on the screen
rotateX(xRot); // apply the rotations
rotateZ(yRot);
fill(200); // set the fill color
box(100); // draw the cube
}
void serialEvent(Serial myPort) {
try{
// this function is called whenever new data is available
// read the incoming data from the serial port
String data = myPort.readString(); // read the data as a string
// print the incoming data to the console if it is not an empty string
if (data != null) {
println(data);
// cleanup / remove whitespace
data = data.trim();
// split the string into separate values
String[] values = split(data, ',');
if (values.length >= 2){
// convert the values to floats and store them in the rotation variables
xRot = radians(float(values[0]));
yRot = radians(float(values[1]));
}else{
println("received unexpected number of values");
printArray(values);
}
}
} catch (Exception e){
println("error reading serial:");
e.printStackTrace();
}
}
(If the above still produces serial errors I'd also write a separate test that doesn't use the servos, just in case internally some servo pwm timing/interrupts alongside accelerometer data polling interferes with serial communication for some reason.)
(AFAIK there is no full IMU support on the micro::bit (e.g. accelerometer + gyroscope + magnetometer (+ ideally sensor fusion)), just accelerometer + magnetometer. If you want to get basic rotation data, but don't care for full 3D orientation of the device should suffice. Otherwise you'd need an IMU (e.g BNO055 or newer) which you can connect to the micro via I2C (but will also probably need to implement the communications protocol to the sensor if someone else hasn't done so already).(In theory I see there's Python support for the Nordic nRF52840 chipset, however microbit uses nRF51822 for v1 and nRF52833 for v2 :/). Depending on your application you might want to switch to a different microcontroller altogether. (for example the official Arduino 33 BLE has a built-in accelerometer (and Python support) (and even supports TensorFlow Lite))
Since I do not have a microbit I tested your Processing code using an Arduino UNO at 9600 baud rate. The following serialEvent() function runs without error:
void serialEvent(Serial myPort) {
String data = myPort.readStringUntil('\n');
if (data != null) {
String inStr = trim(data);
String[] values = split(inStr, ',');
printArray(values);
// convert the values to floats and store them in the rotation variables
xRot = radians(float(values[0]));
yRot = radians(float(values[1]));
zRot = radians(float(values[2]));
}
}
Arduino code:
byte val1 = 0;
byte val2 = 0;
byte val3 = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
val1 += 8;
val2 += 4;
val3 += 2;
String s = String(String(val1) + "," + String(val2) + "," + String(val3));
Serial.println(s);
}
Thank you very much George Profenza, it works perfectly well now!
I just had to fix some errors in the code.
Here's the functional code if anyone has this problem later :
import processing.serial.*; // import the serial library
Serial myPort; // create a serial object
float xRot = 0; // variables to store the rotation angles
float yRot = 0;
void setup() {
size(400, 400, P3D); // set the size of the window and enable 3D rendering
String portNames[] = Serial.list();
printArray(portNames);
String portName = portNames[0]; // get the name of the first serial port
try {
myPort = new Serial(this, portName, 115200); // open a connection to the serial port
myPort.bufferUntil('\n');
}
catch (Exception e) {
println("error opening serial port " + portName + "\ndouble check USB is connected and the port isn't already open in another app");
e.printStackTrace();
}
}
void draw() {
background(255); // clear the screen
translate(width/2, height/2, 0); // center the cube on the screen
rotateX(xRot); // apply the rotations
rotateZ(yRot);
fill(200); // set the fill color
box(100); // draw the cube
}
void serialEvent(Serial myPort) {
try {
// this function is called whenever new data is available
// read the incoming data from the serial port
String data = myPort.readString(); // read the data as a string
// print the incoming data to the console if it is not an empty string
if (data != null) {
println(data);
// cleanup / remove whitespace
data = data.trim();
// split the string into separate values
String[] values = split(data, ',');
if (values.length >= 2) {
// convert the values to floats and store them in the rotation variables
xRot = radians(float(values[0]));
yRot = radians(float(values[1]));
} else {
println("received unexpected number of values");
printArray(values);
}
}
}
catch (Exception e) {
println("error reading serial:");
e.printStackTrace();
}
}
As for the Micro:Bit, I didn't have to change the code at all...
I assume their was an error with the Z axis since we basically just removed removed that...

How to fill a rectangle with some color along with printing a string in Processing console?

I'm developing a GUI for Arduino mega 2560 using Processing (control p5 library).
My board senses analog pin A0 and continuously displays its value as string in console. If a specific digital pin goes high then It sends the error string to processing console and waits for reset to be pressed.
Ex: A1-B1 error press reset
If A1-B1 is error then I want my GUI to fill the rectangle with red along with displaying string
" A1-B1 error press reset"
How to I do this?
Here's my processing code
import java.util.*;
import at.mukprojects.console.*;
Console console;
import processing.serial.*;
Serial port;
import controlP5.*;
ControlP5 cp5;
int myColorBackground = color(0, 0, 0);
float k,l;
String val;
int i;
char a;
void setup() {
size(800,600);
frame.setResizable(true);
smooth();
noStroke();
printArray(Serial.list());
port = new Serial(this,Serial.list()[0],9600);
port.bufferUntil(10);
cp5 = new ControlP5(this); //init gui lib
console = new Console(this); //init console
console.start();
}
void draw() {
background(myColorBackground);
fill(250, 131, 3); //text color
console.draw();
k= (width*0.75);
l=(0.25*height)-50;
fill(0);
stroke(250, 131, 1);
rect(k+20, l+20, 12,12);
fill(250, 131, 3);
textFont(font, 16);
text("A1-B1", k+100, l+20);
}
void serialEvent(Serial myPort) {
while(port.available()>0){
val = port.readStringUntil(10);
}
if (val!=null)
{
println(val);
}
}
The best advice we can give you is to break your problem down into smaller steps and take those pieces on one at a time.
For example, can you create a simple sketch that displays a message after the mouse has been clicked? Forget about the Arduino for a minute and just get this working by itself. It might look something like this:
boolean mouseWasPressed = false;
void draw(){
if(mouseWasPressed){
background(255, 0 , 0);
}
}
void mousePressed(){
mouseWasPressed = true;
}
Separately from that, get a sketch working that just shows the Arduino message in the console. It sounds like you might already have a lot of that done, but try to isolate it in a small example program.
When you have both of those working separately, then you can start thinking about combining them into one program. And if you get stuck, you can post a MCVE showing exactly which step you're stuck on. Good luck.

Serial COM Port Selection by DropDownList in processing

I wrote a program in Processing 2.1.2 to establish a communication via serial Port between two machines. On my laptop, it was working fine but on my desktop where more than one serial ports are available, it is not detecting my functional serial COM port.
So now I want them to appear on Combo Button and I will able to select one from them.
Can you guide me on how do I resolve this issue?
import processing.serial.*;
String input;
Serial port;
void setup() {
size(448, 299,P3D);
println(Serial.list());
port = new Serial(this,Serial.list()[0], 9600);
port.bufferUntil('\n');
}
void draw() {
background(0);
}
void serialEvent(Serial port)
{
input = port.readString();
if(input != null) {
String[] values = split(input, " ");
println(values[0]);
println(values[1]);
println(values[2]);
}
}
As mentioned in the comment, it is possible to use a UI library to display a dropdown. First you have to choose a library, like for example controlP5 which is very popular with Processing. You may choose to use Swing with a native look & feel or G4P. That's totally up to you.
After that it should be a matter of plugging the serial ports list into the dropdown and opening the serial connection on the dropdown listener/callback.
Bellow is a proof of concept sketch based on the controlP5dropdownlist example that comes with the library:
import processing.serial.*;
import controlP5.*;
ControlP5 cp5;
DropdownList serialPortsList;
Serial serialPort;
final int BAUD_RATE = 9600;
void setup() {
size(700, 400,P3D);
String[] portNames = Serial.list();
cp5 = new ControlP5(this);
// create a DropdownList
serialPortsList = cp5.addDropdownList("serial ports").setPosition(10, 10).setWidth(200);
for(int i = 0 ; i < portNames.length; i++) serialPortsList.addItem(portNames[i], i);
}
void controlEvent(ControlEvent theEvent) {
// DropdownList is of type ControlGroup.
// A controlEvent will be triggered from inside the ControlGroup class.
// therefore you need to check the originator of the Event with
// if (theEvent.isGroup())
// to avoid an error message thrown by controlP5.
if (theEvent.isGroup()) {
// check if the Event was triggered from a ControlGroup
println("event from group : "+theEvent.getGroup().getValue()+" from "+theEvent.getGroup());
//check if there's a serial port open already, if so, close it
if(serialPort != null){
serialPort.stop();
serialPort = null;
}
//open the selected core
String portName = serialPortsList.getItem((int)theEvent.getValue()).getName();
try{
serialPort = new Serial(this,portName,BAUD_RATE);
}catch(Exception e){
System.err.println("Error opening serial port " + portName);
e.printStackTrace();
}
}
else if (theEvent.isController()) {
println("event from controller : "+theEvent.getController().getValue()+" from "+theEvent.getController());
}
}
void draw() {
background(128);
}
Also notice any existing connection will be closed when choosing a new serial port and errors handling opening the serial port are handled so the program doesn't crash in case there are issues.
For example, on OSX you get bluetooth serial ports, which may or may not be available or of use:
for processing 3.3.7 doesn't work at all for one string
String portName = serialPortsList.getItem((int)theEvent.getValue()).getName();
So i spent a lot of my neurons and nervs, but my fix is getName change toString();
and
String portName = serialPortsList.getItem((int)theEvent.getValue()).toString();
I don't understand why getName() gives me "The function doesnt exist" but toString works properly. Anybody can explain?
For variable:
String[] portNames = Serial.list();
change to global variable:
String[] portNames;
In:
void setup()
change:
String[] portNames = Serial.list();
to:
portNames = Serial.list();
In code:
String portName = serialPortsList.getItem((int)theEvent.getValue()).toString();
change to:
String portName =portNames.toString();

MousePressed drawing ellipse in tuio

Hi if anyone could help me out i would be very grateful, i have a sketch that will enable a user to draw graffiti on a screen with a wireless spray can. At the minute, with the tuio code installed, when the user presses the mouse button, a spray sound is made.. but i am having difficulty in the sketch creating an ellipse when presses the mouse button.
This is my code;
import ddf.minim.spi.*;
import ddf.minim.signals.*;
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.ugens.*;
import ddf.minim.effects.*;
Minim minim;
AudioPlayer player;
AudioInput input;
/*TUIO processing demo - part of the reacTIVision project
http://reactivision.sourceforge.net/
Copyright (c) 2005-2009 Martin Kaltenbrunner <mkalten#iua.upf.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You shgould have greceived a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// we need to import the TUIO library
// and declare a TuioProcessing client variable
import TUIO.*;
TuioProcessing tuioClient;
import java.util.*; //ADD THIS LINE TO BE ABLE TO USE TUIOCLIENT WITH PROCESSING 2+
// these are some helper variables which are used
// to create scalable graphical feedback
float cursor_size = 15;
float object_size = 60;
float table_size = 760;
float scale_factor = 1;
PFont font;
//declare a boolean to check mouse click
boolean drag = false;
int n=0;
int size[]= {20,40};
int sizeChosen;
boolean inside = false;
PImage bg;
PImage img;
PGraphics pg;
import controlP5.*;
ControlP5 cp5;
boolean mp = true;
void setup ()
{
size(1000,1000);//size(screen.width, screen.height).
smooth();
noStroke();
fill(0);
loop();
frameRate(30);
hint(ENABLE_NATIVE_FONTS);
font = createFont("Arial",18);
scale_factor = height/table_size;
// we create an instance of the TuioProcessing client
// since we add "this" class as an argument the TuioProcessing class expects
// an implementation of the TUIO callback methods (see below)
tuioClient = new TuioProcessing(this);
ellipseMode( CENTER);
//smooth();
noCursor();
background(170);
bg = loadImage("brickwall.jpg");
background(bg);
img = loadImage("instructions.jpg");
image (img,30,40,THUMB_SIZE, THUMB_SIZE);
cp5 = new ControlP5(this);//screenshot button
cp5.addButton("Save Graffiti Artwork").setPosition(0,650).setSize(200,100);//screenshot details
minim = new Minim(this);
player = minim.loadFile("spray_close.wav");
input = minim.getLineIn();
}
void draw() {
if (mp = true);
ellipse(255,0,255,0);
background(bg);
textFont(font,18*scale_factor);
float obj_size = object_size*scale_factor;
float cur_size = cursor_size*scale_factor;
Vector tuioObjectList = tuioClient.getTuioObjects();
for (int i=0;i<tuioObjectList.size();i++) {
TuioObject tobj = (TuioObject)tuioObjectList.elementAt(i);
noStroke();
fill(0);
pushMatrix();
translate(tobj.getScreenX(width), tobj.getScreenY(height));
rotate(tobj.getAngle());
// ellipse(-obj_size/2, -obj_size/2, obj_size, obj_size);
popMatrix();
//fill(255);
text(""+tobj.getSymbolID(), tobj.getScreenX(width), tobj.getScreenY(height));
if (mousePressed) {
ellipse(255,0,255,0);
// printIn("Pink");
//mouse press 1
if (tobj.getSymbolID()==12) {
ellipse(255,0,255,0);
}
}
}
Vector tuioCursorList = tuioClient.getTuioCursors();
for (int i=0;i<tuioCursorList.size();i++) {
TuioCursor tcur = (TuioCursor)tuioCursorList.elementAt(i);
Vector pointList = tcur.getPath();
if (pointList.size()>0) {
stroke(0, 0, 255);
TuioPoint start_point = (TuioPoint)pointList.firstElement();
;
for (int j=0;j<pointList.size();j++) {
TuioPoint end_point = (TuioPoint)pointList.elementAt(j);
line(start_point.getScreenX(width), start_point.getScreenY(height), end_point.getScreenX(width), end_point.getScreenY(height));
start_point = end_point;
}
stroke(192, 192, 192);
fill(192, 192, 192);
ellipse( tcur.getScreenX(width), tcur.getScreenY(height), cur_size, cur_size);
fill(0);
text(""+tcur.getCursorID(), tcur.getScreenX(width)-5, tcur.getScreenY(height)+5);
}
}
if (drag) //if drag = true, i-e if mouse click is holding, ellipse are drawing according the mouse's position
{
fill(#FF00FF); //black color
ellipse(mouseX, mouseY, 50,50); //draw ellipse with x and y mouse's position + size 10*10
//or line strokeWeight(3);stroke(0);line(mouseX,mouseY,25,25);
}
//draw palette size
for(n=0;n<2;n++)
{
fill(0);
ellipse(360,10+n*40,20*(n+1),20*(n+1));
}
}
//size selector
void mousePressed() {
//bDrawFullSize = true;
if (inside==true){
sizeChosen=size[n];
}
player.play();
mp = true;
}
void mouseReleased() {
//bDrawFullSize = true;
drag = false;
player.close();
//since close closes the file, we need to load the sound effect again.
player = minim.loadFile("spray_close.wav");
}
//function "drag and drop"
void mouseDragged() {
drag = true;
}
// these callback methods are called whenever a TUIO event occurs
// called when an object is added to the scene
void addTuioObject(TuioObject tobj) {
println("add object "+tobj.getSymbolID()+" ("+tobj.getSessionID()+") "+tobj.getX()+" "+tobj.getY()+" "+tobj.getAngle());
}
// called when an object is removed from the scene
void removeTuioObject(TuioObject tobj) {
println("remove object "+tobj.getSymbolID()+" ("+tobj.getSessionID()+")");
}
// called when an object is moved
void updateTuioObject (TuioObject tobj) {
println("update object "+tobj.getSymbolID()+" ("+tobj.getSessionID()+") "+tobj.getX()+" "+tobj.getY()+" "+tobj.getAngle()
+" "+tobj.getMotionSpeed()+" "+tobj.getRotationSpeed()+" "+tobj.getMotionAccel()+" "+tobj.getRotationAccel());
}
// called when a cursor is added to the scene
void addTuioCursor(TuioCursor tcur) {
println("add cursor "+tcur.getCursorID()+" ("+tcur.getSessionID()+ ") " +tcur.getX()+" "+tcur.getY());
}
// called when a cursor is moved
void updateTuioCursor (TuioCursor tcur) {
println("update cursor "+tcur.getCursorID()+" ("+tcur.getSessionID()+ ") " +tcur.getX()+" "+tcur.getY()
+" "+tcur.getMotionSpeed()+" "+tcur.getMotionAccel());
}
// called when a cursor is removed from the scene
void removeTuioCursor(TuioCursor tcur) {
println("remove cursor "+tcur.getCursorID()+" ("+tcur.getSessionID()+")");
}
// called after each message bundle
// representing the end of an image frame
void refresh(TuioTime bundleTime) {
redraw();
}
void keyPressed() {
endRecord();
background(bg);
// exit();
}
public void saveScreen() {
saveFrame();
player.pause();
}
// returns true if mouse is inside this rectangle
boolean inside(int left, int top, int right, int bottom ) {
if (mouseX>left && mouseX<right && mouseY>top && mouseY<bottom ) {
return true;
}
else {
return false;
}
}
Anything under the function:
void mousePressed() {
//bDrawFullSize = true;
if (inside==true){
sizeChosen=size[n];
}
player.play();
mp = true;
}
is run every frame while mouse is pressed. So you would create an ellipse (or whatever you want) here.
You can put the ellipse generation function inside branching condition that's checking on the mouse pressed state:
if (mousePressed) {
ellipse(random(0,width),random(0,height),random(0,100),random(0,100));
}
put the condition at the end of the Draw function so that it overwrites any background element

How to make a dynamic image at run time?

I'm working on a card game based on the NetBeans platform and I'm struggling to get my head around dynamic images. Why dynamic? Well I want the cards to adjust at run time to changes to the page (i.e. name, text, cost, etc).
My first hack at it was creating a component (JPanel) with labels pre-placed where I loaded the text/image based on the card values. That seems to work fine but then it became troublesome when I thought about some pages having a different look in later editions (meaning not everything would be on the same place).
So I'm trying to get an idea about ways to do this based on some kind of template.
Any idea?
There's a follow-up question at: JList of cards?
Finally I got some time to get back to this and was able to figure out a way using Java 2D tutorial.
The pictures are not near what I will use in my application but serves as proof of concept.
package javaapplication3;
import java.awt.*; import java.awt.font.FontRenderContext; import
java.awt.font.LineBreakMeasurer; import java.awt.font.TextAttribute;
import java.awt.font.TextLayout; import java.awt.image.BufferedImage;
import java.io.File; import java.io.IOException; import
java.net.MalformedURLException; import java.net.URL; import
java.text.AttributedCharacterIterator; import
java.text.AttributedString; import java.util.ArrayList; import
java.util.HashMap; import java.util.logging.Level; import
java.util.logging.Logger; import javax.imageio.ImageIO;
/** * * #author Javier A. Ortiz Bultrón
*/ public class DefaultImageManager {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
// TODO code application logic here
DefaultImageManager manager = new DefaultImageManager();
URL url = DefaultImageManager.class.getResource("weather-rain.png");
manager.getLayers().add(ImageIO.read(url));
url = DefaultImageManager.class.getResource("weather-sun.png");
manager.getLayers().add(ImageIO.read(url));
manager.addText(new Font("Arial", Font.PLAIN, 10), "Many people believe that Vincent van Gogh painted his best works "
+ "during the two-year period he spent in Provence. Here is where he "
+ "painted The Starry Night--which some consider to be his greatest "
+ "work of all. However, as his artistic brilliance reached new "
+ "heights in Provence, his physical and mental health plummeted. ",
200, 150, new Point(0, 0));
manager.generate();
} catch (MalformedURLException ex) {
Logger.getLogger(DefaultImageManager.class.getName()).log(Level.SEVERE,
null, ex);
} catch (IOException ex) {
Logger.getLogger(DefaultImageManager.class.getName()).log(Level.SEVERE,
null, ex);
}
}
/**
* Layers used to create the final image
*/
private ArrayList layers = new ArrayList();
private ArrayList textLayers = new ArrayList();
/**
* #return the layers
*/
public ArrayList<BufferedImage> getLayers() {
return layers;
}
private Dimension getMaxSize() {
int width = 0, height = 0;
for (BufferedImage img : getLayers()) {
if (img.getWidth() > width) {
width = img.getWidth();
}
if (img.getHeight() > height) {
height = img.getHeight();
}
}
return new Dimension(width, height);
}
public void addText(Font font, String text, int height, int width, Point location) {
BufferedImage textImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
HashMap<TextAttribute, Object> map =
new HashMap<TextAttribute, Object>();
map.put(TextAttribute.FAMILY, font.getFamily());
map.put(TextAttribute.SIZE, font.getSize());
map.put(TextAttribute.FOREGROUND, Color.BLACK);
AttributedString aString = new AttributedString(text, map);
AttributedCharacterIterator paragraph = aString.getIterator();
// index of the first character in the paragraph.
int paragraphStart = paragraph.getBeginIndex();
// index of the first character after the end of the paragraph.
int paragraphEnd = paragraph.getEndIndex();
Graphics2D graphics = textImage.createGraphics();
FontRenderContext frc = graphics.getFontRenderContext();
// The LineBreakMeasurer used to line-break the paragraph.
LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);
// Set break width to width of Component.
float breakWidth = width;
float drawPosY = 0;
// Set position to the index of the first character in the paragraph.
lineMeasurer.setPosition(paragraphStart);
// Get lines until the entire paragraph has been displayed.
while (lineMeasurer.getPosition() < paragraphEnd) {
// Retrieve next layout. A cleverer program would also cache
// these layouts until the component is re-sized.
TextLayout layout = lineMeasurer.nextLayout(breakWidth);
// Compute pen x position. If the paragraph is right-to-left we
// will align the TextLayouts to the right edge of the panel.
// Note: this won't occur for the English text in this sample.
// Note: drawPosX is always where the LEFT of the text is placed.
float drawPosX = layout.isLeftToRight()
? 0 : breakWidth - layout.getAdvance();
// Move y-coordinate by the ascent of the layout.
drawPosY += layout.getAscent();
// Draw the TextLayout at (drawPosX, drawPosY).
layout.draw(graphics, drawPosX, drawPosY);
// Move y-coordinate in preparation for next layout.
drawPosY += layout.getDescent() + layout.getLeading();
}
getTextLayers().add(textImage);
}
public void generate() throws IOException {
Dimension size = getMaxSize();
BufferedImage finalImage = new BufferedImage(size.width, size.height,
BufferedImage.TYPE_INT_ARGB);
for (BufferedImage img : getLayers()) {
finalImage.createGraphics().drawImage(img,
0, 0, size.width, size.height,
0, 0, img.getWidth(null),
img.getHeight(null),
null);
}
for(BufferedImage text: getTextLayers()){
finalImage.createGraphics().drawImage(text,
0, 0, text.getWidth(), text.getHeight(),
0, 0, text.getWidth(null),
text.getHeight(null),
null);
}
File outputfile = new File("saved.png");
ImageIO.write(finalImage, "png", outputfile);
}
/**
* #return the textLayers
*/
public ArrayList<BufferedImage> getTextLayers() {
return textLayers;
}
/**
* #param textLayers the textLayers to set
*/
public void setTextLayers(ArrayList<BufferedImage> textLayers) {
this.textLayers = textLayers;
} }
It still needs some refining specially on the placement of the text but it works. I guess I can implement a xml format to store all this information so is easily configurable. In the example below suns are drawn on top of rain, and the text is on top of all that. For my application each layer will build together the page I want.
Here are the images I used:
And the final result:

Resources