banner



How To Draw A Star In Java

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

(Original post by makaveli33)
Tin I simply draw a fancy drawing with Java, volition that be enough to share your lawmaking?

Lol, im but coding it now anyhow.
+ No just accept a think nigh it =P...All you're doing is drawing lines from where the user specified lol, i even gave a hint earlier of a way of doing it with arrays.

K, gotta become out but i'll pose the stuff tomorrow.

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

You will mail service it tommorow, promise?

can you non use drawPolygon? either add together the coordinates manually or use an array.

I tried entering the coordinates manually simply I struggled.

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

ok then this got me interested and did some googling

a star can exist made from a regular shape. so five pointed star tin exist made from pentagon, 6 pointed star from hexagon and and then on

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

then drawing a regular shape of N sides is easy (or easier, at least).

Lawmaking:

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

not sure about the trig... haven't done whatsoever of this for ages and that lawmaking is off the superlative of my head.

anyhoo that lawmaking *should* get the 10/y coords of each betoken in a regular shape which *should* also exist the coords of your star

now information technology'due south just a instance of joining the dots. bring together them one later on the other and you get a regular shape. for a 5 point star, you join them skipping one out... if you get me. so indicate 1 connects to bespeak 3, two -> 4, 3 -> 5, 4 -> i

Image

hopefully that explains that. but you are looking for a solution for North pointed star... i don't know this only from what i tin can tell the number of vertices you lot skip when joining the dots is the nearly possible, providing yous do not cross the 180 caste line. well that doesn't make any sense. with the star above, draw an imaginary line from the point at the acme, through the middle of the star and downwardly to the bottom. points which the height point connects to are the ones closest to the reverse side.

wow i suck at explaining things verbally without just rambling.

anyhow you lot can go this number with

Code:

int skippedVertices = 179.9 // angle;

(// = carve up discarding the rest)
why 179.9? just a hunch only i recollect 180 would cause issues with angles that fit exactly in to 180 (ie 8 sided = 45 degrees = four skipped vertices if you employ the value 180, which is wrong if you draw it on a bit of paper like i did - seriosuly guys pen and paper FTMFW.)

well. that was fun. in one case again, i have no way of testing this stuff other than a calculator and a bit of paper, so no guarantees that it works

Thanks for sharing.

Information technology must be simpler than that though.

All information technology 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 washed any Swing for over a year. I've attached 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, only hopefully you can understand it.

Image

Okay, since I was bored I decided to find out if I could 'port' Baron's algorithm to PHP.

PHP Code:

<?php
$noPoints
= 5 ;
$innerRadius = 100 ;
$outerRadius = 200 ;
$drawCircles = false ;
$drawDots = false ; $imageSize = ( 2 * $outerRadius ) + l ;
$middle = $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 , $centre , $centre , 2 * $innerRadius , two * $innerRadius , 0 , 0 , $red );
imagearc ( $img , $centre , $center , two * $outerRadius , ii * $outerRadius , 0 , 0 , $ruby );
}

for (

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

    if (

$drawDots ) {
imagefilledarc ( $img , $innerX , $innerY , 5 , 5 , 0 , 0 , $black , IMG_ARC_PIE );
imagefilledarc ( $img , $outerX , $outerY , five , 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 - one ? - $noPoints + 1 : ane ); imageline ( $img , $starDots [ 'innerX' ][ $zz ], $starDots [ 'innerY' ][ $zz ], $starDots [ 'outerX' ][ $zz ], $starDots [ 'outerY' ][ $zz ], $blackness );
imageline ( $img , $starDots [ 'innerX' ][ $zz ], $starDots [ 'innerY' ][ $zz ], $starDots [ 'outerX' ][ $zz + $actress ], $starDots [ 'outerY' ][ $zz + $extra ], $black );
}
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 understand what yous guys did, and besides how on earth did you make that star and then complicated all it takes is a couple of lines drawn through graphics

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

aye, it's only lines. the complicated bit comes in when y'all accept to effigy out where to draw the lines to make a star. the even more complicated bit is that the star tin can have whatsoever number of points

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

Okay, here is the pseudocode with comments, hopefully that volition help you understand.

Before that though, you need to understand the following: The star is generated using two circles, the points are determined by dividing two*pi (a full circumvolve) past the number of points.

So, for 5 points: 2pi/5 would exist the 'separation angle' between each point on the Outer Circle.

We volition accept some other circle which is smaller (ideally half the radius of the outer circle) and this will accept v points as well! Then separation angle = 5pi/2 BUT the divergence is that it will exist placed 'in between' the outer circle'due south points. Here have a look at this picture show which illustrates what I mean:

Image

Now, here'south the pseudocode:

PHP Code:

var noPoints = 5 ; // How many points should the star accept?
var innerRadius = 100 ; // The radius in pixels of the inner circle
var outerRadius = 200 ; // The radius in pixels of the outer circumvolve
var drawCircles = imitation ; // Do nosotros desire the 2 circles fatigued on screen? (Simply for guideline purposes)
var drawDots = false ; // Practise we desire the 'connecting dots' fatigued on screen? (Just for guideline purposes)

 // Summate the prototype size, which should be twice the Outer Radius (as information technology's the biggest) and some more than pixels, I went for +50.

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

// Generate a blank image of imageSize past imageSize pixels (a perfect foursquare prototype in other words)

create_new_image ( imageSize , imageSize ); // Make full this paradigm with a white background
fill_image ( 0 , 0 , white ); // If drawCircles = true, so describe 2 complete circles at origin x = eye, y = centre with red color
// Draw one for innerRadius (diameter = 2 * radius) and i for outerRadius
if ( drawCircles ) {
draw_circle ( centre , centre , 2 * innerRadius , 2 * innerRadius , red );
draw_circle ( centre , centre , 2 * outerRadius , 2 * outerRadius , ruddy );
}
// Loop for 0 to noPoints (exclusive, so thats 0 to 4 for noPoints = 5, etc)
for (var ii = 0 ; ii < noPoints ; ii ++) {
// Calculate the 10 coordinate of where the ii'th point should be
    // This is only maths trig, look into polar coordinates if y'all don't know what is happening here.
    // Centre is added to shift the coordinate to the correct position.
    // In this case we also multiply the ii value by 0.v in order 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 ))) + centre ;
// Same thing here merely now we summate the y coordinate (hence the utilize of sin as opposed to cos)
innerY = innerRadius * sin ( deg2rad (( ii + 0.5 ) * ( 360 / noPoints ))) + heart ; // Same thing as above but at present for Outer Circle
    // AND this time we DON'T multiply by 0.5, as we don't need to considering we have shifted the Inner Circle points
    // So these don't need to be shifted
outerX = outerRadius * cos ( deg2rad ( ii * ( 360 / noPoints ))) + middle ;
// Y coordinate
outerY = outerRadius * sin ( deg2rad ( ii * ( 360 / noPoints ))) + heart ; // deg2rad() past the way converts from degrees to radians

    // If drawDots = truthful, then draw the ii'th point at x=innerX, y=innerY
    // And another ane at x=outerX, y=outerY (for the Outer Circumvolve)

if ( drawDots ) {
draw_circle_filled_in ( innerX , innerY , v , 5 , black ); // The 5, 5 is the horizontal and vertical height of this filled circumvolve.
draw_circle_filled_in ( outerX , outerY , five , 5 , black ); // And then call up of it equally a small black coloured circle with radius 2.5
} // Finally store the calculated inner and outer coordinates for the ii'th indicate in a 2nd array chosen 'starDots'
    // Make certain y'all place them at the finish of the assortment. (In PHP [] acts equally button into array)
starDots [ 'innerX' ][] = innerX ;
starDots [ 'innerY' ][] = innerY ;
starDots [ 'outerX' ][] = outerX ;
starDots [ 'outerY' ][] = outerY ;
}
// Loop for 0 to noPoints (sectional, so thats 0 to 4 for noPoints = 5, etc)
// What nosotros're really doing is looping for the number of elements in the starDots assortment. But since this will always be equal to
// noPoints, there'due south no demand to do unneccessary calculation
for (var zz = 0 ; zz < noPoints ; zz ++) {
// We have to draw two lines, one connecting from innerDot zz to outerDot zz
    // AND another one from innerDot zz to outerDot zz+1 (the next dot)
    // So that'southward 2 lines per loop
    // In total 2*noPoints lines, which is geometrically correct
    // But if we are at the end of the array, and we try to connect to outerDot + 1, we volition try to
    // access a non-existing element. That's what this if cheque does, if we are on the last element,
    // and then give united states of america -(noPoints + one). Which is the value we demand to add together to outerDot in order to access the 0th element aka the beginning dot/point
    // of outerDot
if ( zz == noPoints ) { // If we are on the last chemical element
var extra = 1 ; // Add one to access adjacent dot
} else {
        var
extra = - noPoints + ane ; // Add this value in order the access the 0th chemical element (aka the beginning dot)
} // Draw line from innerDot to outerDot
draw_line ( starDots [ 'innerX' ][ zz ], starDots [ 'innerY' ][ zz ], starDots [ 'outerX' ][ zz ], starDots [ 'outerY' ][ zz ], blackness ); // 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 prototype to screen

Does that make it clear?

In all fairness, this is a piece of cake way of drawing it. I tin can't meet it exist any simpler than this, unless you take a magical built-in role called: draw_star();

Also, to tackle problems like these. You need to grab a paper and pen, and depict a star. So await at things which are common for stars. Endeavour to derive expressions for them and define the maths behind it. And but the then, you lot should start programming.

A circle is a star with infinite points with two 'guideline' circles with equal radius, in reality this is probably not true. Simply you could recall of information technology as that if it helps you understand the to a higher place code.

Can y'all go far in Java and not in PHP?

(Original post by makaveli33)
Can you make it in Java and not in PHP?

If you're asking whether I accept the ability to do that, and then yes.
If you lot're actually asking me to make it, then: Well, Baron kinda already has done that... And in that location'south zip wrong with his coding. And then I don't really see why information technology would be needed.

(Original post by makaveli33)
Tin can you make information technology in Java and not in PHP?

Yar, I fastened the source Java code I used in that nil file. Later on seeing darkraver'southward code I realised I'd unnecessarily manually fatigued the circles. Like in dark raver's PHP code, Graphics in Java also has a ane liner for drawing circles, so that would be a comeback to make.

I only made the change above and also deleted the 'CirclePoint' class I'd made. Java already has a 'Point.Double' class that did the aforementioned job.

I also rotated the star -90 degrees so it is the correct fashion upwards now.

Here'south the 2 classes with the algorithm. I won't bother posting the GUI or Validation classes.

PHP Lawmaking:

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

public course

StarRenderer {

        individual

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 ( Colour . Black );
renderPointList ( getStarPoints (), graphics );
    }

    private

void renderCircle ( Graphics2D graphics , double radius ) {
graphics . setPaint ( Colour . Ruby );
double diameter = 2 * radius ; graphics . draw (new Ellipse2D . Double ( backingForm . getOriginX () - radius , backingForm . getOriginY () - radius , bore , 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 ( innerPoint );
        }

        render

starPoints ;
    }

    private

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:

package util ; import coffee . awt . geom . Point2D ;

public class

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

        return new

Point2D . Double ( x , y );
    }
}

lol, i made my one for fun.

Code:

import pyglet, math  form Star():     def __init__( self, x, y, n=5, radius=32 ):         cocky.drawSequence = []         self.vertexList = []         cocky.n = due north         angle = 360.0 / n         skippedVertices = int( 179.ix // angle )                  for i in range(n):             cocky.vertexList.append(                 10 + math.cos( math.pi * i * angle / 180 ) * radius )             self.vertexList.suspend(                 y + math.sin( math.pi * i * angle / 180 ) * radius )             self.drawSequence.append( i )             self.drawSequence.append(( i + skippedVertices ) % n )      def draw( self ):         pyglet.graphics.draw_indexed(             self.n, pyglet.gl.GL_LINES,             cocky.drawSequence,             ('v2f', cocky.vertexList)         )  stars = [     Star( 100, 100, 5, 50 ),     Star( 500, 200, 7, 100 ),     Star( 250, 300, 10, 125 ) ]  window = pyglet.window.Window()  @window.event 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: webbtrus1947.blogspot.com

0 Response to "How To Draw A Star In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel