How to make a single task into parallel thread - java

I am having this piece of code to generate a picture of drawing, but I also try to implement this task by using thread.
Here is original code
public class Starter extends Application {
private static final int CANVAS_WIDTH = 700;
private static final int CANVAS_HEIGHT = 600;
private static final int X_OFFSET = 25;
private static final int Y_OFFSET = 25;
private static double MANDELBROT_RE_MIN = -2;
private static double MANDELBROT_RE_MAX = 1;
private static double MANDELBROT_IM_MIN = -1.2;
private static double MANDELBROT_IM_MAX = 1.2;
#Override
public void start(Stage primaryStage) {
Pane fractalRootPane = new Pane();
Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
paintSet(canvas.getGraphicsContext2D(),
MANDELBROT_RE_MIN,
MANDELBROT_RE_MAX,
MANDELBROT_IM_MIN,
MANDELBROT_IM_MAX);
fractalRootPane.getChildren().add(canvas);
Scene scene = new Scene(fractalRootPane, CANVAS_WIDTH + 2 * X_OFFSET, CANVAS_HEIGHT + 2 * Y_OFFSET);
scene.setFill(Color.BLACK);
primaryStage.setTitle("Mandelbrot Set");
primaryStage.setScene(scene);
primaryStage.show();
}
private void paintSet(GraphicsContext ctx, double reMin, double reMax, double imMin, double imMax) {
double precision = Math.max((reMax - reMin) / CANVAS_WIDTH, (imMax - imMin) / CANVAS_HEIGHT);
int convergenceSteps = 50;
for (double c = reMin, xR = 0; xR < CANVAS_WIDTH; c = c + precision, xR++) {
for (double ci = imMin, yR = 0; yR < CANVAS_HEIGHT; ci = ci + precision, yR++) {
double convergenceValue = checkConvergence(ci, c, convergenceSteps);
double t1 = (double) convergenceValue / convergenceSteps;
double c1 = Math.min(255 * 2 * t1, 255);
double c2 = Math.max(255 * (2 * t1 - 1), 0);
if (convergenceValue != convergenceSteps) {
ctx.setFill(Color.color(c2 / 255.0, c1 / 255.0, c2 / 255.0));
} else {
ctx.setFill(Color.PURPLE); // Convergence Color
}
ctx.fillRect(xR, yR, 1, 1);
}
}
}
private int checkConvergence(double ci, double c, int convergenceSteps) {
double z = 0;
double zi = 0;
for (int i = 0; i < convergenceSteps; i++) {
double ziT = 2 * (z * zi);
double zT = z * z - (zi * zi);
z = zT + c;
zi = ziT + ci;
if (z * z + zi * zi >= 4.0) {
return i;
}
}
return convergenceSteps;
}
public static void main(String[] args) {
launch(args);
}
}
Here is what I have altered into Thread class.
public class ThreadTest extends Thread {
// Size of the canvas for the Mandelbrot set
private static final int CANVAS_WIDTH = 700;
private static final int CANVAS_HEIGHT = 600;
// Left and right border
private static final int X_OFFSET = 25;
// Top and Bottom border
private static final int Y_OFFSET = 25;
// Values for the Mandelbro set
private static double MANDELBROT_RE_MIN = -2;
private static double MANDELBROT_RE_MAX = 1;
private static double MANDELBROT_IM_MIN = -1.2;
private static double MANDELBROT_IM_MAX = 1.2;
#Override
public void run(){
Stage primaryStage = new Stage();
Pane fractalRootPane = new Pane();
Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
paintSet(canvas.getGraphicsContext2D(),
MANDELBROT_RE_MIN,
MANDELBROT_RE_MAX,
MANDELBROT_IM_MIN,
MANDELBROT_IM_MAX);
fractalRootPane.getChildren().add(canvas);
Scene scene = new Scene(fractalRootPane, CANVAS_WIDTH + 2 * X_OFFSET, CANVAS_HEIGHT + 2 * Y_OFFSET);
scene.setFill(Color.BLACK);
primaryStage.setTitle("Mandelbrot Set");
primaryStage.setScene(scene);
primaryStage.show();
}
private void paintSet(GraphicsContext ctx, double reMin, double reMax, double imMin, double imMax) {
double precision = Math.max((reMax - reMin) / CANVAS_WIDTH, (imMax - imMin) / CANVAS_HEIGHT);
int convergenceSteps = 50;
for (double c = reMin, xR = 0; xR < CANVAS_WIDTH; c = c + precision, xR++) {
for (double ci = imMin, yR = 0; yR < CANVAS_HEIGHT; ci = ci + precision, yR++) {
double convergenceValue = checkConvergence(ci, c, convergenceSteps);
double t1 = (double) convergenceValue / convergenceSteps;
double c1 = Math.min(255 * 2 * t1, 255);
double c2 = Math.max(255 * (2 * t1 - 1), 0);
if (convergenceValue != convergenceSteps) {
ctx.setFill(Color.color(c2 / 255.0, c1 / 255.0, c2 / 255.0));
} else {
ctx.setFill(Color.PURPLE); // Convergence Color
}
ctx.fillRect(xR, yR, 1, 1);
}
}
}
/**
* Checks the convergence of a coordinate (c, ci) The convergence factor
* determines the color of the point.
*/
private int checkConvergence(double ci, double c, int convergenceSteps) {
double z = 0;
double zi = 0;
for (int i = 0; i < convergenceSteps; i++) {
double ziT = 2 * (z * zi);
double zT = z * z - (zi * zi);
z = zT + c;
zi = ziT + ci;
if (z * z + zi * zi >= 4.0) {
return i;
}
}
return convergenceSteps;
}
public static void main(String[] args) {
ThreadTest t1 = new ThreadTest();
t1.start();
}
}
Is there are any better way to achieve this task into parallel mode?

Related

Breakout brick and paddle collision in Java

I'm working on a Breakout game, and I'm having a brick collision problem. The ball bounces off the wall, oar and brick. However, when the ball touches the oar, the oar disappears, although I seem to have prescribed that the ball in this case should rebound. I'm really stuck on this one. How can I fix it?
public class Breakout extends WindowProgram {
/**
* Width and height of application window in pixels
*/
public static final int APPLICATION_WIDTH = 400;
public static final int APPLICATION_HEIGHT = 600;
/**
* Dimensions of game board (usually the same)
*/
private static final int WIDTH = APPLICATION_WIDTH;
private static final int HEIGHT = APPLICATION_HEIGHT;
/**
* Dimensions of the paddle
*/
private static final int PADDLE_WIDTH = 60;
private static final int PADDLE_HEIGHT = 10;
/**
* Offset of the paddle up from the bottom
*/
private static final int PADDLE_Y_OFFSET = 30;
/**
* Number of bricks per row
*/
private static final int NBRICKS_PER_ROW = 10;
/**
* Number of rows of bricks
*/
private static final int NBRICK_ROWS = 10;
/**
* Separation between bricks
*/
private static final int BRICK_SEP = 4;
/**
* Width of a brick
*/
private static final int BRICK_WIDTH =
(WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;
/**
* Height of a brick
*/
private static final int BRICK_HEIGHT = 8;
/**
* Radius of the ball in pixels
*/
private static final int BALL_RADIUS = 10;
private static final int DIAMETER = 2 * BALL_RADIUS;
/**
* Offset of the top brick row from the top
*/
private static final int BRICK_Y_OFFSET = 70;
/**
* Number of turns
*/
private static final int NTURNS = 3;
private static final double DX = 1;
RandomGenerator rgen = RandomGenerator.getInstance();
private void moveBall(GOval o) {
double vx;
double vy = 1;
vx = rgen.nextDouble(1.0, 3.0);
if (rgen.nextBoolean(0.5))
vx = -vx;
while (o.getY() < HEIGHT) {
if (ballAboveRoof(o) && vy < 0) {
vy = -vy;
}
if (ballBehindWallR(o) && vx > 0) {
vx = -vx;
}
if (ballBehindWallL(o) && vx < 0) {
vx = -vx;
}
if (ballBelowFloor(o)) {
GLabel l = new GLabel("GAME OVER");
l.setColor(Color.RED);
l.setFont("Verdana-30");
l.setLocation(((getWidth() - l.getWidth()) / 2), ((getHeight() + l.getAscent()) / 2));
add(l);
break;
}
if (getCollidingObject(o) == paddle) {
println("Paddle");
vy = -vy;
}
if (getCollidingObject(o) != brick) {
println("Brick");
remove(getCollidingObject(o));
}
o.move(vx, vy);
pause(10);
}
}
GRect bricks;
GRect brick;
private GRect paddle;
GOval o;
// GObject collider = getCollidingObject(o);
private GObject getCollidingObject(GObject o) {
double x = o.getX(), y = o.getY();
if (getElementAt(x, y) != null) {
return getElementAt(x, y);
} else if (getElementAt(x, y + BALL_RADIUS * 2) != null) {
return getElementAt(x, y + BALL_RADIUS * 2);
} else if (getElementAt(x + BALL_RADIUS * 2, y + BALL_RADIUS * 2) != null) {
return getElementAt(x + BALL_RADIUS * 2, y + BALL_RADIUS * 2);
} else if (getElementAt(x + BALL_RADIUS * 2, y) != null) {
return getElementAt(x + BALL_RADIUS * 2, y);
} else {
return null;
}
}
private boolean ballAboveRoof(GOval o) {
return o.getY() <= 0;
}
private boolean ballBelowFloor(GOval o) {
return o.getY() + o.getHeight() >= getHeight();
}
private boolean ballBehindWallL(GOval o) {
return o.getX() <= 0;
}
private boolean ballBehindWallR(GOval o) {
return o.getX() + o.getWidth() >= getWidth();
}
private GOval addBall() {
int x = (getWidth() - DIAMETER) / 2;
int y = (getHeight() - DIAMETER) / 2;
GOval o = new GOval(x, y, DIAMETER, DIAMETER);
o.setFilled(true);
o.setFillColor(Color.BLACK);
o.setColor(Color.BLACK);
add(o);
return o;
}
private void addPaddle() {
paddle = new GRect((WIDTH - PADDLE_WIDTH) / 2.0, HEIGHT - PADDLE_Y_OFFSET, PADDLE_WIDTH, PADDLE_HEIGHT);
paddle.setColor(Color.BLACK);
paddle.setFilled(true);
paddle.setFillColor(Color.BLACK);
add(paddle);
}
public void mouseMoved(MouseEvent mouseEvent) {
int newX = mouseEvent.getX();
if (newX - (double) PADDLE_WIDTH / 2 >= 0 && newX + (double) PADDLE_WIDTH / 2 <= getWidth()) {
paddle.setLocation(newX - (double) PADDLE_WIDTH / 2, HEIGHT - PADDLE_Y_OFFSET);
}
}
private void addBricks() {
for (int i = 0; i < NBRICK_ROWS; i++) {
for (int j = 0; j < NBRICKS_PER_ROW; j++) {
addBrick(i, j);
}
}
}
private void addBrick(int i, int j) {
int x = BRICK_SEP / 2;
int n1 = i < NBRICKS_PER_ROW ? 1 : 0;
int n2 = j < NBRICK_ROWS ? 1 : 0;
GRect brick = new GRect(x + i * (BRICK_WIDTH + (BRICK_SEP) * n1), BRICK_Y_OFFSET + j * (BRICK_HEIGHT + BRICK_SEP * n2), BRICK_WIDTH, BRICK_HEIGHT);
brick.setFillColor(Color.BLACK);
brick.setFilled(true);
brick.setColor(Color.BLACK);
add(brick);
}
// #Override
public void run() {
getMenuBar().setVisible(false);
addMouseListeners();
addPaddle();
addBricks();
o = addBall();
moveBall(o);
}
}

stdDraw draw over background java

I am doing this project that simulates the solar system using java's stdDraw. I want to make the change where I can show the trace of the corn, because my ultimate goal is to make this corn fly in a heart shape and if I can draw out the trace of the corn I can present the heart. Right now I've been trying to do it, but it seems like the background image is blocking the trace. And if I comment out the background image, all of the planets will show their trace. I don't know what to do, help!!!
Here is the Object Class:
public class BodyExtreme{
public double xxPos;
public double yyPos;
public double xxVel;
public double yyVel;
public double mass;
public String imgFileName;
private static final double G = 6.67e-11;
public BodyExtreme(double xP, double yP, double xV, double yV, double m, String img){
xxPos = xP;
yyPos = yP;
xxVel = xV;
yyVel = yV;
mass = m;
imgFileName = img;
}
public BodyExtreme(BodyExtreme b){
xxPos = b.xxPos;
yyPos = b.yyPos;
xxVel = b.xxVel;
yyVel = b.yyVel;
mass = b.mass;
imgFileName = b.imgFileName;
}
public double calcDistance(BodyExtreme b) {
double dx = b.xxPos - this.xxPos;
double dy = b.yyPos - this.yyPos;
return Math.sqrt(dx * dx + dy * dy);
}
public double calcForceExertedBy(BodyExtreme b) {
if (this.calcDistance(b) == 0) {
return 0;
} else {
return (G * b.mass * this.mass)/(this.calcDistance(b) * this.calcDistance(b));
}
}
public double calcForceExertedByX(BodyExtreme b) {
return (this.calcForceExertedBy(b) * (b.xxPos - this.xxPos) / this.calcDistance(b));
}
public double calcForceExertedByY(BodyExtreme b) {
return (this.calcForceExertedBy(b) * (b.yyPos - this.yyPos) / this.calcDistance(b));
}
public double calcNetForceExertedByX(BodyExtreme[] b) {
int i = 0;
double sum = 0;
while (i < b.length) {
if (this.equals(b[i])) {
sum += 0;
i += 1;
} else {
sum = sum + this.calcForceExertedByX(b[i]);
i += 1;
}
} return sum;
}
public double calcNetForceExertedByY(BodyExtreme[] b) {
int i = 0;
double sum = 0;
while (i < b.length) {
if (this.equals(b[i])) {
sum += 0;
i += 1;
} else {
sum = sum + this.calcForceExertedByY(b[i]);
i += 1;
}
} return sum;
}
public void update(double dt, double fX, double fY) {
double ax = fX / this.mass;
double ay = fY / this.mass;
double vx = this.xxVel + dt * ax;
double vy = this.yyVel + dt * ay;
double px = this.xxPos + dt * vx;
double py = this.yyPos + dt * vy;
this.xxPos = px;
this.yyPos = py;
this.xxVel = vx;
this.yyVel = vy;
}
public void draw() {
StdDraw.picture(this.xxPos, this.yyPos, "images/" + this.imgFileName);
}
public void lonelyplanet_update1(){
this.xxPos = this.xxPos + 45000000;
this.yyPos = this.yyPos + 100000000;
this.draw();
}
}
Here is the Main method class:
import java.util.Scanner;
public class NBodyExtreme{
public static double readRadius(String name) {
In in = new In(name);
int NumPlanets = in.readInt();
double Size = in.readDouble();
return Size;
}
public static BodyExtreme[] readBodies(String name) {
In in = new In(name);
int NumPlanets = in.readInt();
double Size = in.readDouble();
BodyExtreme[] bodies = new BodyExtreme[NumPlanets];
int i = 0;
while (i < NumPlanets) {
bodies[i] = new BodyExtreme(in.readDouble(), in.readDouble(), in.readDouble(), in.readDouble(), in.readDouble(), in.readString());
i += 1;
}
return bodies;
}
public static void main(String[] args) {
double T = Double.parseDouble(args[0]); /** Stoping Time */
double dt = Double.parseDouble(args[1]); /** Time Step */
String filename = args[2];
BodyExtreme[] bodies = readBodies(filename); /** Array of Bodies */
double radius = readRadius(filename); /** Canvas Radius */
In in = new In(filename);
int NumPlanets = in.readInt(); /** Number of Planets */
String imageToDraw = "images/starfield.jpg"; /** Background */
StdDraw.enableDoubleBuffering();
StdDraw.setScale(-2*radius, 2*radius);
StdDraw.clear();
StdDraw.picture(0, 0, imageToDraw); /** Draw Initial Background */
StdDraw.show();
int k = 0;
while (k < NumPlanets-1) { /** Draw Planets */
bodies[k].draw();
k += 1;
}
StdDraw.enableDoubleBuffering();
double time = 0.0;
while (time < T) {
double[] xForces = new double[NumPlanets-1];
double[] yForces = new double[NumPlanets-1];
int i = 0;
while (i < NumPlanets-1) {
xForces[i] = bodies[i].calcNetForceExertedByX(bodies);
yForces[i] = bodies[i].calcNetForceExertedByY(bodies);
i += 1;
}
i = 0;
while (i < NumPlanets-1) {
bodies[i].update(dt, xForces[i], yForces[i]);
i += 1;
}
bodies[NumPlanets-1].lonelyplanet_update1();
bodies[NumPlanets-1].draw();
StdDraw.show();
StdDraw.picture(0, 0, imageToDraw);
int j = 0;
while (j < NumPlanets) {
bodies[j].draw();
j += 1;
}
StdDraw.show();
StdDraw.pause(10);
}
time += dt;
}
}
This is what happens when the trace of route is blocked with the background image:
This is what happens when the trace is not blocked, but I only want the corn's trace not to be blokcekd.
you have a flaw in your animation logic:
to animate your screen you have to
update the model (each element, eg. backgroud or bodY),
then draw each model by using StdDraw.picture(..) and
finally make that content visible (by using StdDraw.show();)
for each time step in your animation (while (time < T){..}) you have to do all three steps.
public static void main(String[] args) {
...
StdDraw.enableDoubleBuffering(); //it's enough to call this only once!
double time = 0.0;
while (time < T) {
//do all the update stuff first, as shown in your code above
//then draw ONCE the BackGround:
StdDraw.picture(0, 0, imageToDraw);
//then draw all the planets (yes, i missed one)
while (j < NumPlanets) {
bodies[j].draw();
j += 1;
}
//finally make all the previous drawing visible
StdDraw.show();
//wait a bit for the next animation step
StdDraw.pause(10);
time += dt;
}
}

JavaFx draw Image inside in Pane

Hi I want to drawing image inside in Pane , when a bounds are heigh I want to cut image. This image consists of tile. One tile size is 256. Now my full image is bigger tham Pane. I don't know how I can cut image.
Hi I want to draw one large image, which consists of tiles. One tile has dimensions of 256x256. This image is in Pane. At this time, image dimensions are larger than the dimension Pane. I do not know how to do to draw only in Pane. Thanks for help
public class TestURLImage8 {
public static ArrayList<BusStop2> list = new ArrayList<>();
public static ArrayList<PositionTilesAndURLPaths> positionTilesAndURLPathsList = new ArrayList<>();
public static HashMap<String, Image> imgCache = new HashMap<>();
public static double lat;
public static double lon;
public static double deltaY;
public static double deltaX;
public static double positionX;
public static double positionY;
public static int[] imageCount = getCountImage();
public static int [] countImage = countImage();
public static int []x = new int [countImage[0]];
public static int []y = new int [countImage[1]];
private File file = new File("C:/Users/022/workspace22/EkranLCD/res/images/kropka.png");
private Image bus = new Image(file.toURI().toString());
static ArrayList<UtlToImageConverter> threadList = new ArrayList<>();
public TestURLImage8(Pane pane) {
}
/**
* Method use to get count of image what we need
* #return
*/
private static int[] getCountImage(){
int xImageCount = (int) Math.ceil(Main4.width/256);
int yImageCount = (int) Math.ceil(Main4.height/256);
return new int[] {xImageCount, yImageCount};
}
/**
* Method use to get count of tiles
* #return
*/
public static int[] countImage(){
int xImageCount = imageCount[0];
int yImageCount = imageCount[1];
if(xImageCount-1 %2 != 0){
xImageCount = xImageCount + 2;
}
if(yImageCount-1 %2 != 0){
yImageCount = yImageCount + 2;
}
return new int[] {xImageCount, yImageCount};
}
/**
* Method use to get tiles
* #param lat
* #param lon
* #return
*/
private static ArrayList<BusStop2> getTiles(double lat, double lon ){
int [] numberTile = getTileNumber(lat, lon, Config.mapZoom);
int a1 = 1;
int a2 = 1;
int a3 = 1;
int a4 = 1;
x[0] = numberTile[0];
y[0] = numberTile[1];
for (int i = 1; i<x.length; i++){
if(i%2==0){
x[i] = numberTile[0]+(a1);
a1++;
}
else{
x[i] = numberTile[0]-(a2);
a2++;
}
}
for (int i = 1; i<y.length; i++){
if(i%2==0){
y[i] = numberTile[1]+(a3);
a3++;
}
else{
y[i] = numberTile[1]-(a4);
a4++;
}
}
for(int i = 0 ; i<x.length ; i++){
for (int j = 0 ;j<y.length ; j++ ){
list.add(new BusStop2(x[i], y[j], x[0] - x[i], y[0]-y[j]));
}
}
return list;
}
/**
*
* #param list
* #return
*/
private static ArrayList<PositionTilesAndURLPaths> getImgPositionAndURLsPath(ArrayList<BusStop2> list){
for(BusStop2 bus : list){
positionTilesAndURLPathsList.add(new PositionTilesAndURLPaths(256*bus.getX(), 256*bus.getY(),
Config.mapPath + "/" + bus.getA() + "/" + bus.getB() + ".png"));
}
return positionTilesAndURLPathsList;
}
public static int [] getTileNumber(final double lat, final double lon, final int zoom) {
int xtile = (int)Math.floor( (lon + 180) / 360 * (1<<zoom) ) ;
int ytile = (int)Math.floor( (1 - Math.log(Math.tan(Math.toRadians(lat)) + 1 / Math.cos(Math.toRadians(lat))) / Math.PI) / 2 * (1<<zoom) ) ;
if (xtile < 0)
xtile=0;
if (xtile >= (1<<zoom))
xtile=((1<<zoom)-1);
if (ytile < 0)
ytile=0;
if (ytile >= (1<<zoom))
ytile=((1<<zoom)-1);
return new int[] {xtile, ytile};
}
static double tile2lon(int x, int z) {
return x / Math.pow(2.0, z) * 360.0 - 180;
}
static double tile2lat(int y, int z) {
double n = Math.PI - (2.0 * Math.PI * y) / Math.pow(2.0, z);
return Math.toDegrees(Math.atan(Math.sinh(n)));
}
public void start(Pane pane ,double lat, double lon) throws Exception {
int [] tiles= getTileNumber(lat, lon, Config.mapZoom);
Canvas canvas = new Canvas(Config.xSize, Config.ySize);
GraphicsContext gc = canvas.getGraphicsContext2D();
int [] aa =getTileNumber(lat,lon, Config.mapZoom);
getTiles(lat,lon);
getImgPositionAndURLsPath(list);
ExecutorService executor = Executors.newFixedThreadPool(10);
ArrayList<UtlToImageConverter2> threadList = new ArrayList<>();
for(PositionTilesAndURLPaths url : positionTilesAndURLPathsList){
threadList.add(new UtlToImageConverter2(url.getPath()));
}
try {
executor.invokeAll(threadList);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(imgCache.size());
System.out.println( aa[0] + " " + aa[1] );
deltaX = tile2lon(tiles[0] + 1 , Config.mapZoom) - tile2lon(tiles[0], Config.mapZoom);
deltaY = tile2lat(tiles[1], Config.mapZoom) - tile2lat(tiles[1] + 1 , Config.mapZoom);
positionX = (lon - tile2lon(tiles[0], Config.mapZoom)) * Config.imgSize/deltaX;
positionY = (tile2lat(tiles[1], Config.mapZoom) - lat) * Config.imgSize/deltaY;
gc.drawImage(bus,847.0-100 ,621.0-100);
gc.strokeText("aalala", 847.0-10 ,621.0-10);
for(PositionTilesAndURLPaths pos : getImgPositionAndURLsPath(list)){
gc.drawImage(imgCache.get(pos.getPath()),Config.xSize/2-pos.getX()-Config.imgSize/2 ,(Config.ySize/2)- pos.getY()-Config.imgSize/2, Config.imgSize, Config.imgSize);
System.out.println(pos.getX() + " " + pos.getY());
}
gc.drawImage(bus,Config.xSize/2-Config.imgSize/2-Config.markWidth/2+positionX, Config.ySize/2+positionY-Config.imgSize/2-Config.markHeight/2, Config.markWidth, Config.markHeight);
pane.getChildren().add(canvas);
}
#SuppressWarnings("unused")
public static void clear(){
for(PositionTilesAndURLPaths url : positionTilesAndURLPathsList){
url = null;
}
positionTilesAndURLPathsList.clear();
threadList.clear();
for(UtlToImageConverter utl : threadList){
utl = null;
}
for(BusStop2 bus :list){
bus = null;
}
list.clear();
}
}
There are multiple options to display a part of a image in JavaFX:
When using a Canvas node, use the correct drawImage, i.e. the one that does not scale the image to the target rectangle. e.g.
Rectangle2D rectInSource = ...
Rectangle2D targetRect = ...
gc.drawImage(image,
rectInSource.getMinX(),
rectInSource.getMinY(),
rectInSource.getWidth(),
rectInSource.getHeight(),
targetRect.getMinX(),
targetRect.getMinY(),
targetRect.getWidth(),
targetRect.getHeight());
Alternatively you could also use a ImageView for displaying part of a Image by setting the viewport property accordingly:
ImageView imageView = new ImageView(image);
imageView.setViewport(rectInSource);
// ----------- Only required, if rescaling is desired -----------
imageView.setFitWidth(targetRect.getWidth());
imageView.setFitHeight(targetRect.getHeight());
// --------------------------------------------------------------
imageView.relocate(targetRect.getMinX(), targetRect.getMinY());
pane.getChildren().add(imageView);
rectInSource denotes the part of the image that should be displayed, targetRect the position where it should be drawn.

draw mandlebrot onto bitmap

I am currently converting java code into c# code and i have it almost working i think but I am trying to draw the mandlebrot onto the bitmap but nothing is displaying . The form pops up but nothing is drawn onto it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Assignment1
{
public partial class Form1 : Form
{
public Form1()
{
init();
start();
stop();
destroy();
InitializeComponent();
}
public struct HSBColor
{
float h;
float s;
float b;
int a;
public HSBColor(float h, float s, float b)
{
this.a = 0xff;
this.h = Math.Min(Math.Max(h, 0), 255);
this.s = Math.Min(Math.Max(s, 0), 255);
this.b = Math.Min(Math.Max(b, 0), 255);
}
public HSBColor(int a, float h, float s, float b)
{
this.a = a;
this.h = Math.Min(Math.Max(h, 0), 255);
this.s = Math.Min(Math.Max(s, 0), 255);
this.b = Math.Min(Math.Max(b, 0), 255);
}
public float H
{
get { return h; }
}
public float S
{
get { return s; }
}
public float B
{
get { return b; }
}
public int A
{
get { return a; }
}
public Color Color
{
get
{
return FromHSB(this);
}
}
public static Color FromHSB(HSBColor hsbColor)
{
float r = hsbColor.b;
float g = hsbColor.b;
float b = hsbColor.b;
if (hsbColor.s != 0)
{
float max = hsbColor.b;
float dif = hsbColor.b * hsbColor.s / 255f;
float min = hsbColor.b - dif;
float h = hsbColor.h * 360f / 255f;
if (h < 60f)
{
r = max;
g = h * dif / 60f + min;
b = min;
}
else if (h < 120f)
{
r = -(h - 120f) * dif / 60f + min;
g = max;
b = min;
}
else if (h < 180f)
{
r = min;
g = max;
b = (h - 120f) * dif / 60f + min;
}
else if (h < 240f)
{
r = min;
g = -(h - 240f) * dif / 60f + min;
b = max;
}
else if (h < 300f)
{
r = (h - 240f) * dif / 60f + min;
g = min;
b = max;
}
else if (h <= 360f)
{
r = max;
g = min;
b = -(h - 360f) * dif / 60 + min;
}
else
{
r = 0;
g = 0;
b = 0;
}
}
return Color.FromArgb
(
hsbColor.a,
(int)Math.Round(Math.Min(Math.Max(r, 0), 255)),
(int)Math.Round(Math.Min(Math.Max(g, 0), 255)),
(int)Math.Round(Math.Min(Math.Max(b, 0), 255))
);
}
}
private const int MAX = 256; // max iterations
private const double SX = -2.025; // start value real
private const double SY = -1.125; // start value imaginary
private const double EX = 0.6; // end value real
private const double EY = 1.125; // end value imaginary
private static int x1, y1, xs, ys, xe, ye;
private static double xstart, ystart, xende, yende, xzoom, yzoom;
private static bool action, rectangle, finished;
private static float xy;
private Image picture;
private Graphics g1;
private Cursor c1, c2;
//private HSB HSBcol=new HSB();
public void init() // all instances will be prepared
{
//HSBcol = new HSB();
this.Size = new Size(640,480);
finished = false;
//addMouseListener(this);
//addMouseMotionListener(this);
//c1 = new Cursor(Cursor.WAIT_CURSOR);
//c2 = new Cursor(Cursor.CROSSHAIR_CURSOR);
x1 = this.Width;
y1 = this.Height;
xy = (float)x1 / (float)y1;
Bitmap img = new Bitmap(1, 1);
g1 = Graphics.FromImage(img);
finished = true;
}
public void destroy() // delete all instances
{
if (finished)
{
//removeMouseListener(this);
//removeMouseMotionListener(this);
picture = null;
g1 = null;
c1 = null;
c2 = null;
GC.Collect(); // garbage collection
}
}
public void start()
{
action = false;
rectangle = false;
initvalues();
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
mandelbrot();
}
public void stop()
{
}
public void paint(Graphics g)
{
update(g);
}
public void update(Graphics g)
{
g.DrawImage(picture, 0, 0);
if (rectangle)
{
Pen WhitePen = new Pen(Color.White);
if (xs < xe)
{
if (ys < ye) g.DrawRectangle(WhitePen, xs, ys, (xe - xs), (ye - ys));
else g.DrawRectangle(WhitePen, xs, ye, (xe - xs), (ys - ye));
}
else
{
if (ys < ye) g.DrawRectangle(WhitePen, xe, ys, (xs - xe), (ye - ys));
else g.DrawRectangle(WhitePen, xe, ye, (xs - xe), (ys - ye));
}
}
}
private void mandelbrot() // calculate all points
{
int x, y;
float h, b, alt = 0.0f;
Pen FractalPen;
action = false;
//SetCursor(c1);
//showStatus("Mandelbrot-Set will be produced - please wait...");
for (x = 0; x < x1; x+=2)
for (y = 0; y < y1; y++)
{
h = pointcolour(xstart + xzoom * (double)x, ystart + yzoom * (double)y); // color value
if (h != alt)
{
b = 1.0f - h * h; // brightnes
///djm added
//HSBcol.fromHSB(h,0.8f,b); //convert hsb to rgb then make a Java Color
Color color = HSBColor.FromHSB(new HSBColor(h * 255, 0.8f * 255, b * 255)); // VERY IMPORTANT
//g1.setColor(col);
//djm end
//djm added to convert to RGB from HSB
//g1.setColor(Color.getHSBColor(h, 0.8f, b));
//djm test
//Color col = Color.getHSBColor(h,0.8f,b);
//int red = col.getRed();
//int green = col.getGreen();
//int blue = col.getBlue();
//djm
alt = h;
FractalPen = new Pen(color);
g1.DrawLine(FractalPen, x, y, x + 1, y);
}
}
//showStatus("Mandelbrot-Set ready - please select zoom area with pressed mouse.");
//setCursor(c2);
action = true;
}
private float pointcolour(double xwert, double ywert) // color value from 0.0 to 1.0 by iterations
{
double r = 0.0, i = 0.0, m = 0.0;
int j = 0;
while ((j < MAX) && (m < 4.0))
{
j++;
m = r * r - i * i;
i = 2.0 * r * i + ywert;
r = m + xwert;
}
return (float)j / (float)MAX;
}
private void initvalues() // reset start values
{
xstart = SX;
ystart = SY;
xende = EX;
yende = EY;
if ((float)((xende - xstart) / (yende - ystart)) != xy )
xstart = xende - (yende - ystart) * (double)xy;
}
/*public void mousePressed(MouseEvent e)
{
e.consume();
if (action)
{
xs = e.getX();
ys = e.getY();
}
}
public void mouseReleased(MouseEvent e)
{
int z, w;
e.consume();
if (action)
{
xe = e.getX();
ye = e.getY();
if (xs > xe)
{
z = xs;
xs = xe;
xe = z;
}
if (ys > ye)
{
z = ys;
ys = ye;
ye = z;
}
w = (xe - xs);
z = (ye - ys);
if ((w < 2) && (z < 2)) initvalues();
else
{
if (((float)w > (float)z * xy)) ye = (int)((float)ys + (float)w / xy);
else xe = (int)((float)xs + (float)z * xy);
xende = xstart + xzoom * (double)xe;
yende = ystart + yzoom * (double)ye;
xstart += xzoom * (double)xs;
ystart += yzoom * (double)ys;
}
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
mandelbrot();
rectangle = false;
repaint();
}
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
e.consume();
if (action)
{
xe = e.getX();
ye = e.getY();
rectangle = true;
repaint();
}
}
public void mouseMoved(MouseEvent e)
{
}
public String getAppletInfo()
{
return "fractal.class - Mandelbrot Set a Java Applet by Eckhard Roessel 2000-2001";
}*/
}
}
Bitmap img = new Bitmap(1, 1);
This could be the problem. You forgot to replace it with width,height. Like this
Bitmap img = new Bitmap(x1, y1);
call your paint method like this (picturebox is not needed, but for me it was fastest when painting with winforms:
Rectangle r = new Rectangle();
var g = pictureBox1.CreateGraphics();
var pea = new PaintEventArgs(g, r);
yourPaintMethod(pea);
calls:
public void yourPaintMethod(PaintEventArgs e ) {
Graphics g = e.Graphics;
Pen pBlack = new Pen(Color.Black, 1);
g.DrawLine(pBlack........ etc.

How to draw android animated Doughnut chart

Here I have use 'HoloGraph' Library for Doughnut chart But Now I need to show with animation. Please suggest me How can I do it?
I have done without animation
Here's how i finally did it after two days of search with help of this library https://github.com/Ken-Yang/AndroidPieChart
And equations to center text done with help of my friends and alot of search
on MainActivity onCreate or oncreateView if you are using fragments:
PieChart pie = (PieChart) rootView.findViewById(R.id.pieChart);
ArrayList<Float> alPercentage = new ArrayList<Float>();
alPercentage.add(2.0f);
alPercentage.add(8.0f);
alPercentage.add(20.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.85f);
alPercentage.add(9.15f);
try {
// setting data
pie.setAdapter(alPercentage);
// setting a listener
pie.setOnSelectedListener(new OnSelectedLisenter() {
#Override
public void onSelected(int iSelectedIndex) {
Toast.makeText(getActivity(),
"Select index:" + iSelectedIndex,
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
if (e.getMessage().equals(PieChart.ERROR_NOT_EQUAL_TO_100)) {
Log.e("kenyang", "percentage is not equal to 100");
}
}
public class PieChart extends View {
public interface OnSelectedLisenter {
public abstract void onSelected(int iSelectedIndex);
}
private OnSelectedLisenter onSelectedListener = null;
private static final String TAG = PieChart.class.getName();
public static final String ERROR_NOT_EQUAL_TO_100 = "NOT_EQUAL_TO_100";
private static final int DEGREE_360 = 360;
private static String[] PIE_COLORS = null;
private static int iColorListSize = 0;
ArrayList<Float> array;
private Paint paintPieFill;
private Paint paintPieBorder;
private Paint paintCenterCircle;
private ArrayList<Float> alPercentage = new ArrayList<Float>();
private int mCenterX = 320;
private int mCenterY = 320;
private int iDisplayWidth, iDisplayHeight;
private int iSelectedIndex = -1;
private int iCenterWidth = 0;
private int iShift = 0;
private int iMargin = 0; // margin to left and right, used for get Radius
private int iDataSize = 0;
private Canvas canvas1;
private RectF r = null;
private RectF centerCircle = null;
private float fDensity = 0.0f;
private float fStartAngle = 0.0f;
private float fEndAngle = 0.0f;
float fX;
float fY;
public PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
PIE_COLORS = getResources().getStringArray(R.array.colors);
iColorListSize = PIE_COLORS.length;
array = new ArrayList<Float>();
fnGetDisplayMetrics(context);
iShift = (int) fnGetRealPxFromDp(30);
iMargin = (int) fnGetRealPxFromDp(40);
centerCircle = new RectF(200, 200, 440, 440);
// used for paint circle
paintPieFill = new Paint(Paint.ANTI_ALIAS_FLAG);
paintPieFill.setStyle(Paint.Style.FILL);
// used for paint centerCircle
paintCenterCircle = new Paint(Paint.ANTI_ALIAS_FLAG);
paintCenterCircle.setStyle(Paint.Style.FILL);
paintCenterCircle.setColor(Color.WHITE);
// used for paint border
paintPieBorder = new Paint(Paint.ANTI_ALIAS_FLAG);
paintPieBorder.setStyle(Paint.Style.STROKE);
paintPieBorder.setStrokeWidth(fnGetRealPxFromDp(3));
paintPieBorder.setColor(Color.WHITE);
Log.i(TAG, "PieChart init");
}
// set listener
public void setOnSelectedListener(OnSelectedLisenter listener) {
this.onSelectedListener = listener;
}
float temp = 0;
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.i(TAG, "onDraw");
float centerX = (r.left + r.right) / 2;
float centerY = (r.top + r.bottom) / 2;
float radius1 = (r.right - r.left) / 2;
radius1 *= 0.5;
float startX = mCenterX;
float startY = mCenterY;
float radius = mCenterX;
float medianAngle = 0;
Path path = new Path();
for (int i = 0; i < iDataSize; i++) {
// check whether the data size larger than color list size
if (i >= iColorListSize) {
paintPieFill.setColor(Color.parseColor(PIE_COLORS[i
% iColorListSize]));
} else {
paintPieFill.setColor(Color.parseColor(PIE_COLORS[i]));
}
fEndAngle = alPercentage.get(i);
// convert percentage to angle
fEndAngle = fEndAngle / 100 * DEGREE_360;
// if the part of pie was selected then change the coordinate
if (iSelectedIndex == i) {
canvas.save(Canvas.MATRIX_SAVE_FLAG);
float fAngle = fStartAngle + fEndAngle / 2;
double dxRadius = Math.toRadians((fAngle + DEGREE_360)
% DEGREE_360);
fY = (float) Math.sin(dxRadius);
fX = (float) Math.cos(dxRadius);
canvas.translate(fX * iShift, fY * iShift);
}
canvas.drawArc(r, fStartAngle, fEndAngle, true, paintPieFill);
float angle = (float) ((fStartAngle + fEndAngle / 2) * Math.PI / 180);
float stopX = (float) (startX + (radius/2) * Math.cos(angle));
float stopY = (float) (startY + (radius/2) * Math.sin(angle));
// if the part of pie was selected then draw a border
if (iSelectedIndex == i) {
canvas.drawArc(r, fStartAngle, fEndAngle, true, paintPieBorder);
canvas.drawLine(startX, startY, stopX, stopY, paintPieFill);
canvas.restore();
}
fStartAngle = fStartAngle + fEndAngle;
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// get screen size
iDisplayWidth = MeasureSpec.getSize(widthMeasureSpec);
iDisplayHeight = MeasureSpec.getSize(heightMeasureSpec);
if (iDisplayWidth > iDisplayHeight) {
iDisplayWidth = iDisplayHeight;
}
/*
* determine the rectangle size
*/
iCenterWidth = iDisplayWidth / 2;
int iR = iCenterWidth - iMargin;
if (r == null) {
r = new RectF(iCenterWidth - iR, // top
iCenterWidth - iR, // left
iCenterWidth + iR, // right
iCenterWidth + iR); // bottom
}
if (centerCircle == null) {
// centerCircle=new RectF(left, top, right, bottom);
}
setMeasuredDimension(iDisplayWidth, iDisplayWidth);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// get degree of the touch point
double dx = Math.atan2(event.getY() - iCenterWidth, event.getX()
- iCenterWidth);
float fDegree = (float) (dx / (2 * Math.PI) * DEGREE_360);
fDegree = (fDegree + DEGREE_360) % DEGREE_360;
// get the percent of the selected degree
float fSelectedPercent = fDegree * 100 / DEGREE_360;
// check which pie was selected
float fTotalPercent = 0;
for (int i = 0; i < iDataSize; i++) {
fTotalPercent += alPercentage.get(i);
if (fTotalPercent > fSelectedPercent) {
iSelectedIndex = i;
break;
}
}
if (onSelectedListener != null) {
onSelectedListener.onSelected(iSelectedIndex);
}
invalidate();
return super.onTouchEvent(event);
}
private void fnGetDisplayMetrics(Context cxt) {
final DisplayMetrics dm = cxt.getResources().getDisplayMetrics();
fDensity = dm.density;
}
private float fnGetRealPxFromDp(float fDp) {
return (fDensity != 1.0f) ? fDensity * fDp : fDp;
}
public void setAdapter(ArrayList<Float> alPercentage) throws Exception {
this.alPercentage = alPercentage;
iDataSize = alPercentage.size();
float fSum = 0;
for (int i = 0; i < iDataSize; i++) {
fSum += alPercentage.get(i);
}
if (fSum != 100) {
Log.e(TAG, ERROR_NOT_EQUAL_TO_100);
iDataSize = 0;
throw new Exception(ERROR_NOT_EQUAL_TO_100);
}
}
In Layout:
<com.example.piecharts.PieChart
android:id="#+id/pieChart"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.example.piecharts.PieChart>

Categories

Resources