banner



How To Draw A Star Java

Tin I merely draw a fancy drawing with Java, will that be enough to share your code?

(Original post past makaveli33)
Can I just draw a fancy drawing with Java, will that exist enough to share your code?

Lol, im merely coding it now anyhow.
+ No merely have a call back about it =P...All you lot're doing is drawing lines from where the user specified lol, i even gave a hint before of a way of doing information technology with arrays.

Thousand, gotta go out but i'll pose the stuff tomorrow.

What? Was the hint nearly the caste angle it would be.

You volition post information technology tommorow, promise?

can yous not apply drawPolygon? either add the coordinates manually or utilise an array.

I tried inbound the coordinates manually merely I struggled.

I'm open to anyone else that can evidence me?

ok and then this got me interested and did some googling

a star can be made from a regular shape. then 5 pointed star can exist made from pentagon, vi pointed star from hexagon so on

http://en.wikipedia.org/wiki/Pentagram#Geometry

so drawing a regular shape of North sides is easy (or easier, at to the lowest degree).

Code:

float angle = 360/Northward; float vertices[N][two]; bladder radius = 32;  for (int i = 0; i < Northward; i++) {   vertices[i][0] = cos( toRadians( angle * i )) * radius;   vertices[i][1] = sin( toRadians( angle * i )) * radius; }

not sure nigh the trig... oasis't washed whatever of this for ages and that lawmaking is off the top of my head.

anyhoo that lawmaking *should* get the x/y coords of each point in a regular shape which *should* also be the coords of your star

now it's just a example of joining the dots. join them one subsequently the other and y'all get a regular shape. for a 5 signal star, yous bring together them skipping one out... if you get me. and then point ane connects to point 3, ii -> 4, 3 -> five, iv -> i

Image

hopefully that explains that. but you are looking for a solution for North pointed star... i don't know this but from what i tin tell the number of vertices you skip when joining the dots is the well-nigh possible, providing you do non cross the 180 degree line. well that doesn't make whatsoever sense. with the star in a higher place, describe an imaginary line from the point at the top, through the middle of the star and down to the bottom. points which the top indicate connects to are the ones closest to the opposite side.

wow i suck at explaining things verbally without just rambling.

anyway you tin get this number with

Code:

int skippedVertices = 179.9 // angle;

(// = split up discarding the remainder)
why 179.9? just a hunch but i retrieve 180 would cause problems with angles that fit exactly in to 180 (ie 8 sided = 45 degrees = 4 skipped vertices if yous use the value 180, which is wrong if yous draw it on a fleck of paper similar i did - seriosuly guys pen and paper FTMFW.)

well. that was fun. once once more, i have no fashion of testing this stuff other than a calculator and a bit of paper, so no guarantees that it works

Thanks for sharing.

It must exist simpler than that though.

All it takes is a few drawings of a line and co-ordinates to connect them.

I idea this sounded fun; I'd never tried to programmatically draw a star and hadn't done any Swing for over a year. I've fastened my solution (both the source and a runnable JAR). The JAR is in the zip under /Star/dist/Star.jar.

The source code isn't commented, but hopefully you can empathize it.

Image

Okay, since I was bored I decided to notice out if I could 'port' Businesswoman'southward algorithm to PHP.

PHP Lawmaking:

<?php
$noPoints
= five ;
$innerRadius = 100 ;
$outerRadius = 200 ;
$drawCircles = simulated ;
$drawDots = false ; $imageSize = ( two * $outerRadius ) + 50 ;
$centre = $imageSize / 2 ; $img = imagecreatetruecolor ( $imageSize , $imageSize ); $white = imagecolorallocate ( $img , 255 , 255 , 255 );
$red = imagecolorallocate ( $img , 255 , 0 , 0 );
$black = imagecolorallocate ( $img , 0 , 0 , 0 ); imagefill ( $img , 0 , 0 , $white );
if (
$drawCircles ) {
imagearc ( $img , $middle , $middle , 2 * $innerRadius , 2 * $innerRadius , 0 , 0 , $red );
imagearc ( $img , $centre , $centre , 2 * $outerRadius , 2 * $outerRadius , 0 , 0 , $red );
}

for (

$ii = 0 ; $ii < $noPoints ; $two ++) {
$innerX = $innerRadius * cos ( deg2rad (( $ii + 0.5 ) * ( 360 / $noPoints ))) + $centre ;
$innerY = $innerRadius * sin ( deg2rad (( $ii + 0.v ) * ( 360 / $noPoints ))) + $heart ; $outerX = $outerRadius * cos ( deg2rad ( $two * ( 360 / $noPoints ))) + $eye ;
$outerY = $outerRadius * sin ( deg2rad ( $2 * ( 360 / $noPoints ))) + $centre ;

    if (

$drawDots ) {
imagefilledarc ( $img , $innerX , $innerY , 5 , 5 , 0 , 0 , $blackness , IMG_ARC_PIE );
imagefilledarc ( $img , $outerX , $outerY , v , 5 , 0 , 0 , $black , IMG_ARC_PIE );
    }
$starDots [ 'innerX' ][] = $innerX ;
$starDots [ 'innerY' ][] = $innerY ;
$starDots [ 'outerX' ][] = $outerX ;
$starDots [ 'outerY' ][] = $outerY ;
}

for (

$zz = 0 ; $zz < $noPoints ; $zz ++) {
$extra = ( $zz == $noPoints - 1 ? - $noPoints + i : 1 ); imageline ( $img , $starDots [ 'innerX' ][ $zz ], $starDots [ 'innerY' ][ $zz ], $starDots [ 'outerX' ][ $zz ], $starDots [ 'outerY' ][ $zz ], $black );
imageline ( $img , $starDots [ 'innerX' ][ $zz ], $starDots [ 'innerY' ][ $zz ], $starDots [ 'outerX' ][ $zz + $extra ], $starDots [ 'outerY' ][ $zz + $extra ], $blackness );
}
header ( "Content-type: image/png" );
imagepng ( $img ); imagedestroy ( $img );
?>

Or you can view a demonstration at: http://d3m0.netii.net/star.php

OMG, the worst thing is I dont empathize what y'all guys did, and also how on earth did you make that star so complicated all information technology takes is a couple of lines drawn through graphics

(Original post by makaveli33)
OMG, the worst thing is I dont empathize what y'all guys did, and also how on globe did you lot make that star then complicated all it takes is a couple of lines drawn through graphics

yeah, information technology's simply lines. the complicated bit comes in when y'all have to figure out where to draw the lines to make a star. the fifty-fifty more complicated bit is that the star can have any number of points

(Original post by makaveli33)
OMG, the worst thing is I dont understand what yous guys did, and also how on earth did you make that star so complicated all it takes is a couple of lines fatigued through graphics

Okay, hither is the pseudocode with comments, hopefully that volition help you empathise.

Before that though, you demand to sympathize the following: The star is generated using two circles, the points are determined by dividing 2*pi (a total circle) by the number of points.

And then, for 5 points: 2pi/5 would be the 'separation angle' betwixt each point on the Outer Circle.

We will have another circumvolve which is smaller (ideally half the radius of the outer circle) and this will have 5 points every bit well! Then separation angle = 5pi/ii But the difference is that it will be placed 'in betwixt' the outer circle's points. Here have a look at this picture which illustrates what I mean:

Image

Now, hither'south the pseudocode:

PHP Lawmaking:

var noPoints = 5 ; // How many points should the star have?
var innerRadius = 100 ; // The radius in pixels of the inner circle
var outerRadius = 200 ; // The radius in pixels of the outer circle
var drawCircles = fake ; // Do we want the 2 circles fatigued on screen? (But for guideline purposes)
var drawDots = simulated ; // Practise we want the 'connecting dots' drawn on screen? (But for guideline purposes)

 // Calculate the image size, which should be twice the Outer Radius (as it's the biggest) and some more pixels, I went for +50.

imageSize = ( 2 * outerRadius ) + 50 ;
centre = imageSize / 2 ; // Calculate centre of the image, pretty straightforward.

// Generate a bare epitome of imageSize by imageSize pixels (a perfect square epitome in other words)

create_new_image ( imageSize , imageSize ); // Fill this image with a white background
fill_image ( 0 , 0 , white ); // If drawCircles = true, and so draw 2 complete circles at origin 10 = center, y = heart with carmine colour
// Draw one for innerRadius (diameter = ii * radius) and one for outerRadius
if ( drawCircles ) {
draw_circle ( centre , centre , ii * innerRadius , two * innerRadius , red );
draw_circle ( centre , centre , 2 * outerRadius , 2 * outerRadius , red );
}
// Loop for 0 to noPoints (sectional, so thats 0 to four for noPoints = 5, etc)
for (var ii = 0 ; two < noPoints ; ii ++) {
// Calculate the x coordinate of where the two'th point should exist
    // This is just maths trig, look into polar coordinates if you don't know what is happening here.
    // Eye is added to shift the coordinate to the correct position.
    // In this instance nosotros besides multiply the ii value by 0.five in society to ensure that the points in the Inner Circle
    // appear in the middle of the Outer Circle
innerX = innerRadius * cos ( deg2rad (( ii + 0.5 ) * ( 360 / noPoints ))) + eye ;
// Aforementioned affair hither just now we calculate the y coordinate (hence the apply of sin as opposed to cos)
innerY = innerRadius * sin ( deg2rad (( ii + 0.5 ) * ( 360 / noPoints ))) + centre ; // Aforementioned matter every bit above only now for Outer Circumvolve
    // AND this time nosotros DON'T multiply by 0.5, equally we don't need to because we have shifted the Inner Circumvolve points
    // So these don't need to be shifted
outerX = outerRadius * cos ( deg2rad ( ii * ( 360 / noPoints ))) + centre ;
// Y coordinate
outerY = outerRadius * sin ( deg2rad ( 2 * ( 360 / noPoints ))) + centre ; // deg2rad() past the way converts from degrees to radians

    // If drawDots = true, then draw the ii'thursday betoken at x=innerX, y=innerY
    // And another one at ten=outerX, y=outerY (for the Outer Circle)

if ( drawDots ) {
draw_circle_filled_in ( innerX , innerY , 5 , 5 , black ); // The v, 5 is the horizontal and vertical height of this filled circle.
draw_circle_filled_in ( outerX , outerY , 5 , 5 , black ); // So think of it as a pocket-sized blackness coloured circle with radius 2.5
} // Finally store the calculated inner and outer coordinates for the ii'th signal in a 2nd array called 'starDots'
    // Make sure you place them at the end of the array. (In PHP [] acts as push into array)
starDots [ 'innerX' ][] = innerX ;
starDots [ 'innerY' ][] = innerY ;
starDots [ 'outerX' ][] = outerX ;
starDots [ 'outerY' ][] = outerY ;
}
// Loop for 0 to noPoints (exclusive, and so thats 0 to 4 for noPoints = 5, etc)
// What we're really doing is looping for the number of elements in the starDots array. But since this will e'er be equal to
// noPoints, there's no demand to practice unneccessary calculation
for (var zz = 0 ; zz < noPoints ; zz ++) {
// We accept to draw 2 lines, one connecting from innerDot zz to outerDot zz
    // AND another one from innerDot zz to outerDot zz+one (the adjacent dot)
    // So that's 2 lines per loop
    // In total 2*noPoints lines, which is geometrically right
    // But if we are at the end of the assortment, and nosotros endeavour to connect to outerDot + 1, nosotros will try to
    // access a non-existing element. That's what this if bank check does, if nosotros are on the concluding element,
    // and then give us -(noPoints + 1). Which is the value nosotros need to add to outerDot in society to access the 0th element aka the first dot/point
    // of outerDot
if ( zz == noPoints ) { // If we are on the last element
var extra = 1 ; // Add 1 to access next dot
} else {
        var
actress = - noPoints + 1 ; // Add together this value in club the access the 0th element (aka the offset dot)
} // Depict line from innerDot to outerDot
draw_line ( starDots [ 'innerX' ][ zz ], starDots [ 'innerY' ][ zz ], starDots [ 'outerX' ][ zz ], starDots [ 'outerY' ][ zz ], black ); // Draw line from innerDot to (outerDot + extra)
draw_line ( starDots [ 'innerX' ][ zz ], starDots [ 'innerY' ][ zz ], starDots [ 'outerX' ][ zz + extra ], starDots [ 'outerY' ][ zz + extra ], blackness ); //draw_line(fromX, fromY, toX, toY, color)
} draw_image (); // Draw the paradigm to screen

Does that make it clear?

In all fairness, this is a easy mode of drawing information technology. I can't see it be any simpler than this, unless you have a magical built-in part called: draw_star();

Also, to tackle bug like these. You lot need to grab a paper and pen, and draw a star. Then look at things which are mutual for stars. Try to derive expressions for them and define the maths behind it. And only the then, yous should start programming.

A circumvolve is a star with infinite points with 2 'guideline' circles with equal radius, in reality this is probably non true. Merely you could think of information technology as that if information technology helps you sympathize the above lawmaking.

Tin can you make it in Java and non in PHP?

(Original mail by makaveli33)
Tin can you brand information technology in Java and non in PHP?

If you're request whether I take the ability to do that, and then yes.
If you're actually asking me to make it, and so: Well, Baron kinda already has done that... And there's nothing wrong with his coding. So I don't actually see why it would be needed.

(Original mail past makaveli33)
Tin can you lot make it in Java and not in PHP?

Yar, I attached the source Coffee code I used in that zip file. After seeing darkraver'south lawmaking I realised I'd unnecessarily manually drawn the circles. Similar in dark raver'south PHP code, Graphics in Java also has a one liner for drawing circles, so that would be a improvement to make.

I just made the change above and also deleted the 'CirclePoint' grade I'd made. Java already has a 'Point.Double' grade that did the same chore.

I also rotated the star -90 degrees and so it is the right fashion up at present.

Here's the two classes with the algorithm. I won't bother posting the GUI or Validation classes.

PHP Code:

package render ; import gui . StarValidator . StarBackingForm ;
import coffee . awt . Color ;
import java . awt . Graphics2D ;
import java . awt . geom . Ellipse2D ;
import coffee . awt . geom . GeneralPath ;
import coffee . awt . geom . Point2D ;
import java . util . LinkedList ;
import util . CircleUtil ;

public form

StarRenderer {

        private

StarBackingForm backingForm ;

    public

StarRenderer ( StarBackingForm backingForm ) {
this . backingForm = backingForm ;
    }

    public

void renderStar ( Graphics2D graphics ) {
        if(
backingForm . isDrawCircles ()) {
renderCircle ( graphics , backingForm . getOuterRadius ());
renderCircle ( graphics , backingForm . getInnerRadius ());
        }
graphics . setPaint ( Color . BLACK );
renderPointList ( getStarPoints (), graphics );
    }

    individual

void renderCircle ( Graphics2D graphics , double radius ) {
graphics . setPaint ( Colour . RED );
double diameter = 2 * radius ; graphics . draw (new Ellipse2D . Double ( backingForm . getOriginX () - radius , backingForm . getOriginY () - radius , diameter , diameter ));
    }

    private

void moveLine ( GeneralPath generalPath , Point2D . Double to ) {
generalPath . moveTo ( to . getX (), to . getY ());
    }

    private

void drawLine ( GeneralPath generalPath , Point2D . Double to ) {
generalPath . lineTo ( to . getX (), to . getY ());
    }

    individual

LinkedList < Point2D . Double > getStarPoints () {
LinkedList < Point2D . Double > starPoints = new LinkedList < Point2D . Double >();
double circIncrement = 360.0 / backingForm . getPoints ();

        for(

double outerAngle = - 90 ; starPoints . size () < ( backingForm . getPoints () * ii ); outerAngle += circIncrement ) {
double innerAngle = outerAngle + ( 0.5 * circIncrement );
Point2D . Double outerPoint = CircleUtil . getCircleRadiusPoint ( backingForm . getOriginX (), backingForm . getOriginY (), backingForm . getOuterRadius (), outerAngle );
Point2D . Double innerPoint = CircleUtil . getCircleRadiusPoint ( backingForm . getOriginX (), backingForm . getOriginY (), backingForm . getInnerRadius (), innerAngle );
starPoints . add ( outerPoint );
starPoints . add together ( innerPoint );
        }

        return

starPoints ;
    }

    individual

void renderPointList ( LinkedList < Point2D . Double > starPoints , Graphics2D graphics ) {
GeneralPath generalPath = new GeneralPath ();
moveLine ( generalPath , starPoints . getFirst ());
        for(
Point2D . Double thisPoint : starPoints ) {
drawLine ( generalPath , thisPoint );
        }
drawLine ( generalPath , starPoints . getFirst ());
graphics . draw ( generalPath );
    }
}

PHP Code:

parcel util ; import java . awt . geom . Point2D ;

public form

CircleUtil {
    public static
Point2D . Double getCircleRadiusPoint ( double centreX , double centreY , double radius , double angle ) {
double ten = radius * Math . cos ( Math . toRadians ( bending )) + centreX ;
double y = radius * Math . sin ( Math . toRadians ( angle )) + centreY ;

        return new

Point2D . Double ( ten , y );
    }
}

lol, i made my one for fun.

Code:

import pyglet, math  grade Star():     def __init__( cocky, x, y, n=five, radius=32 ):         self.drawSequence = []         cocky.vertexList = []         self.north = n         bending = 360.0 / due north         skippedVertices = int( 179.nine // angle )                  for i in range(n):             self.vertexList.suspend(                 x + math.cos( math.pi * i * angle / 180 ) * radius )             self.vertexList.append(                 y + math.sin( math.pi * i * angle / 180 ) * radius )             cocky.drawSequence.append( i )             cocky.drawSequence.append(( i + skippedVertices ) % due north )      def draw( self ):         pyglet.graphics.draw_indexed(             self.n, pyglet.gl.GL_LINES,             self.drawSequence,             ('v2f', cocky.vertexList)         )  stars = [     Star( 100, 100, 5, fifty ),     Star( 500, 200, seven, 100 ),     Star( 250, 300, ten, 125 ) ]  window = pyglet.window.Window()  @window.upshot def on_draw():     window.clear()     for star in stars:         star.draw()  pyglet.app.run()

Image

Source: https://www.thestudentroom.co.uk/showthread.php?t=1092919&page=2

Posted by: freemantherwas.blogspot.com

0 Response to "How To Draw A Star Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel