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.
Related
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?
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;
}
}
//I'm trying to draw a new dot every 250 milliseconds but it only draws the dot a single time. I have tried fixing it many times, but it still will only paint a single dot, rather than one after 250 milliseconds. Is this a problem with the timer or the paint method? Here is the code:
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Window extends JPanel{
private int size;
private static double maxValue;
private double elevation;
private double vertV;
public double horizV;
public double gravity;
public double range;
public double time;
public double t = 0;
public Window(int s, double v, double e, double v2, double g,double h,double r,double t){
size = s;
maxValue = v;
elevation = e;
vertV = v2;
gravity = g;
horizV = h;
range = r;
time = t;
setPreferredSize(new Dimension(size, size));
}
public void paintComponent(Graphics g){
g.drawLine(size/25, 0,size/25, size);
g.drawLine(0, size - (size/25), size, size - (size/25));
double[] lines = getLine();
int x = size/5 + (size/25), y = size - (size/25);
int x2 = x;
for(int i = 0; i < 4; i++){
g.drawLine(x, y+5, x, y-5);
g.drawString(lines[i]+"",x-size/50,y+size/30);
x+=x2;
}
int yx = size/25, yy = size - (size/5 + (size/25));
int y2 = size/5 + (size/25);
for(int i=0;i<4;i++){
g.drawLine(yx-5, yy, yx+5, yy);
g.drawString(lines[i]+"",yx-size/25,yy+size/30);
yy -= y2;
}
drawDots(g);
}
//this is the place where i make the dots but it only makes one.
//used to be a for loop but i altered it to an if statement so i could paint one dot at a time
public void drawDots(Graphics g)
{
double ratio = (size-((size/25)*2))/maxValue;
double fx;
double xvalue;
// This for loop is where dots are drawn, each iteration draws one dot. It starts at zero, and counts up to the time variable t.
if(t<=time)
{
t+=0.025;
t = Math.round(t*1000.0)/1000.0;
fx = function(t);
xvalue = xfunction(t);
if(fx >= 0){
System.out.print("Time: " + t + " " + "Range: " + xvalue + " " + "Height: ");
System.out.println(fx);
g.drawLine((int)(size/25+(ratio*xvalue)), (int)((size-(size/25))-(ratio*fx)),
(int)(size/25+(ratio*xvalue)), (int)((size-(size/25))-(ratio*fx)));
}
}
}
//where i make the timer
//250 mill
public void dostuff()
{
int delay = 250;
ActionListener taskPerformer = new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
repaint();
}
};
new Timer(delay, taskPerformer).start();
}
public double xfunction(double t){
double x = 0.0;
x = Math.round(horizV * t * 1000.0)/1000.0;
return x;
}
public double function(double t){
double fx = 0.0;
fx = Math.round((vertV*t + .5*(-(gravity))*(t*t) + elevation)*1000.0)/1000.0;
return fx;
}
private static double[] getLine(){
double increment = maxValue / 4;
double currentLine = 0;
double[] lines = new double[4];
for(int i = 0; i < 4; i++){
currentLine+=increment;
lines[i] = Math.round(currentLine * 10.0)/10.0;
}
return lines;
}
}
This is the original version of the code that displays the projectile's motion, but it does not wait 250 milliseconds between drawing each point:
import javax.swing.JPanel;
import java.awt.*;
public class Window extends JPanel{
private int size;
private static double maxValue;
private double elevation;
private double vertV;
public double horizV;
public double gravity;
public double range;
public double time;
public Window(int s, double v, double e, double v2, double g,double h,double r,double t){
size = s;
maxValue = v;
elevation = e;
vertV = v2;
gravity = g;
horizV = h;
range = r;
time = t;
setPreferredSize(new Dimension(size, size));
}
public void paintComponent(Graphics g){
g.drawLine(size/25, 0,size/25, size);
g.drawLine(0, size - (size/25), size, size - (size/25));
double[] lines = getLine();
int x = size/5 + (size/25), y = size - (size/25);
int x2 = x;
for(int i = 0; i < 4; i++){
g.drawLine(x, y+5, x, y-5);
g.drawString(lines[i]+"",x-size/50,y+size/30);
x+=x2;
}
int yx = size/25, yy = size - (size/5 + (size/25));
int y2 = size/5 + (size/25);
for(int i=0;i<4;i++){
g.drawLine(yx-5, yy, yx+5, yy);
g.drawString(lines[i]+"",yx-size/25,yy+size/30);
yy -= y2;
}
drawDots(g);
}
public void drawDots(Graphics g){
double ratio = (size-((size/25)*2))/maxValue;
double fx;
double xvalue;
// This for loop is where dots are drawn, each iteration draws one dot. It starts at zero, and counts up to the time variable t.
for(double t=0;t<=time; t+=0.025){
t = Math.round(t*1000.0)/1000.0;
fx = function(t);
xvalue = xfunction(t);
if(fx >= 0){
System.out.print("Time: " + t + " " + "Range: " + xvalue + " " + "Height: ");
System.out.println(fx);
g.drawLine((int)(size/25+(ratio*xvalue)), (int)((size-(size/25))-(ratio*fx)),
(int)(size/25+(ratio*xvalue)), (int)((size-(size/25))-(ratio*fx)));
}
}
}
public double xfunction(double t){
double x = 0.0;
x = Math.round(horizV * t * 1000.0)/1000.0;
return x;
}
public double function(double t){
double fx = 0.0;
fx = Math.round((vertV*t + .5*(-(gravity))*(t*t) + elevation)*1000.0)/1000.0;
return fx;
}
private static double[] getLine(){
double increment = maxValue / 4;
double currentLine = 0;
double[] lines = new double[4];
for(int i = 0; i < 4; i++){
currentLine+=increment;
lines[i] = Math.round(currentLine * 10.0)/10.0;
}
return lines;
}
}
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>
I'm trying to begin learning to use Perlin Noise to create a tile map. I'm just beginning so I found some source code online to create an array based on Perlin Noise. So I have an array of good data right now (as far as I know) but I don't understand what kinds of methods can be used to convert this from an array into a tile map.
Does anybody have any examples or sources of any methods to do this?
Here is the code I'm using the generate the array.
package perlin1;
import java.util.Random;
public class ImageWriter {
/** Source of entropy */
private Random rand_;
/** Amount of roughness */
float roughness_;
/** Plasma fractal grid */
private float[][] grid_;
/** Generate a noise source based upon the midpoint displacement fractal.
*
* #param rand The random number generator
* #param roughness a roughness parameter
* #param width the width of the grid
* #param height the height of the grid
*/
public ImageWriter(Random rand, float roughness, int width, int height) {
roughness_ = roughness / width;
grid_ = new float[width][height];
rand_ = (rand == null) ? new Random() : rand;
}
public void initialise() {
int xh = grid_.length - 1;
int yh = grid_[0].length - 1;
// set the corner points
grid_[0][0] = rand_.nextFloat() - 0.5f;
grid_[0][yh] = rand_.nextFloat() - 0.5f;
grid_[xh][0] = rand_.nextFloat() - 0.5f;
grid_[xh][yh] = rand_.nextFloat() - 0.5f;
// generate the fractal
generate(0, 0, xh, yh);
}
// Add a suitable amount of random displacement to a point
private float roughen(float v, int l, int h) {
return v + roughness_ * (float) (rand_.nextGaussian() * (h - l));
}
// generate the fractal
private void generate(int xl, int yl, int xh, int yh) {
int xm = (xl + xh) / 2;
int ym = (yl + yh) / 2;
if ((xl == xm) && (yl == ym)) return;
grid_[xm][yl] = 0.5f * (grid_[xl][yl] + grid_[xh][yl]);
grid_[xm][yh] = 0.5f * (grid_[xl][yh] + grid_[xh][yh]);
grid_[xl][ym] = 0.5f * (grid_[xl][yl] + grid_[xl][yh]);
grid_[xh][ym] = 0.5f * (grid_[xh][yl] + grid_[xh][yh]);
float v = roughen(0.5f * (grid_[xm][yl] + grid_[xm][yh]), xl + yl, yh
+ xh);
grid_[xm][ym] = v;
grid_[xm][yl] = roughen(grid_[xm][yl], xl, xh);
grid_[xm][yh] = roughen(grid_[xm][yh], xl, xh);
grid_[xl][ym] = roughen(grid_[xl][ym], yl, yh);
grid_[xh][ym] = roughen(grid_[xh][ym], yl, yh);
generate(xl, yl, xm, ym);
generate(xm, yl, xh, ym);
generate(xl, ym, xm, yh);
generate(xm, ym, xh, yh);
}
/**
* Dump out as a CSV
*/
public void printAsCSV() {
for(int i = 0;i < grid_.length;i++) {
for(int j = 0;j < grid_[0].length;j++) {
System.out.print(grid_[i][j]);
System.out.print(",");
}
System.out.println();
}
}
/**
* Convert to a Boolean array
* #return the boolean array
*/
public boolean[][] toBooleans() {
int w = grid_.length;
int h = grid_[0].length;
boolean[][] ret = new boolean[w][h];
for(int i = 0;i < w;i++) {
for(int j = 0;j < h;j++) {
ret[i][j] = grid_[i][j] < 0;
}
}
return ret;
}
/** For testing */
public static void main(String[] args) {
ImageWriter n = new ImageWriter(null, 1.0f, 250, 250);
n.initialise();
n.printAsCSV();
}
}
The resulting array is all amounts between 0 and 1.
Again, I'm just looking for how this array can be converted into a tile map.
Any help is appreciated. Thanks