0% found this document useful (0 votes)
13 views18 pages

Java Line and Circle Drawing Algorithms

The document contains Java code implementations for various line and circle drawing algorithms, including DDA, Bresenham's line algorithm, and Mid-Point Circle Drawing. It also covers 2D transformations like rotation and 3D transformations using Java 3D, along with the Cohen-Sutherland algorithm for line clipping. Each section includes example code and outputs for visualizing the results.

Uploaded by

suma29ab
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views18 pages

Java Line and Circle Drawing Algorithms

The document contains Java code implementations for various line and circle drawing algorithms, including DDA, Bresenham's line algorithm, and Mid-Point Circle Drawing. It also covers 2D transformations like rotation and 3D transformations using Java 3D, along with the Cohen-Sutherland algorithm for line clipping. Each section includes example code and outputs for visualizing the results.

Uploaded by

suma29ab
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

// Java Code for DDA line generation

public class Solution {

// function for rounding off the pixels


public static int round(float n) {
if (n - (int) n < 0.5)
return (int) n;
return (int) (n + 1);
}

// Function for line generation


public static void DDALine(int x0, int y0, int x1, int y1) {

// Calculate dx and dy
int dx = x1 - x0;
int dy = y1 - y0;

int step;

// If dx > dy we will take step as dx


// else we will take step as dy to draw the complete
// line
if ([Link](dx) > [Link](dy))
step = [Link](dx);
else
step = [Link](dy);

// Calculate x-increment and y-increment for each step


float x_incr = (float) dx / step;
float y_incr = (float) dy / step;

// Take the initial points as x and y


float x = x0;
float y = y0;

for (int i = 0; i < step; i++) {

// putpixel(round(x), round(y), WHITE);


[Link](round(x) + " " + round(y));
x += x_incr;
y += y_incr;
// delay(10);
}
}

// Driver code
public static void main(String[] args) {

int x0 = 200, y0 = 180, x1 = 180, y1 = 160;

// Function call
DDALine(x0, y0, x1, y1);

}
}

// This code is contributed by ishankhandelwals.

200 180
199 179
198 178
197 177
196 176
195 175
194 174
193 173
192 172
191 171
190 170
189 169
188 168
187 167
186 166
185 165
184 164
183 163
182 162
181 161
// Java program for Bresenhams Line Generation
// Assumptions :

// 1) Line is drawn from left to right.

// 2) x1 < x2 and y1 < y2

// 3) Slope of the line is between 0 and 1.

// We draw a line from lower left to upper

// right.

class GFG {

// function for line generation

static void bresenham(int x1, int y1, int x2, int y2)

int m_new = 2 * (y2 - y1);

int slope_error_new = m_new - (x2 - x1);

for (int x = x1, y = y1; x < = x2; x++) {

[Link](

"

(" + x + ", " + y + ")\n

& quot;);

// Add slope to increment angle formed

slope_error_new += m_new;

// Slope error reached limit, time to

// increment y and update slope error.

if (slope_error_new& gt; = 0) {

y++;

slope_error_new -= 2 * (x2 - x1);


}

// Driver code

public static void main(String[] args)

int x1 = 3, y1 = 2, x2 = 15, y2 = 5;

// Function call

bresenham(x1, y1, x2, y2);

Output

(3,2)
(4,3)
(5,3)
(6,3)
(7,3)
(8,4)
(9,4)
(10,4)
(11,4)
(12,5)
(13,5)
(14,5)
(15,5)

BresenhamCircle
public class BresenhamCircle {

public static void drawCircle(int xc, int yc, int r) {


int x = 0;
int y = r;
int d = 3 - 2 * r; // Initial decision parameter

// Plot the initial point and its symmetric counterparts


plotPoints(xc, yc, x, y);

while (y >= x) {
x++; // Increment x

if (d > 0) { // If the midpoint is outside or on the circle


y--; // Decrement y
d = d + 4 * (x - y) + 10; // Update decision parameter
} else { // If the midpoint is inside the circle
d = d + 4 * x + 6; // Update decision parameter
}

// Plot the points and their symmetric counterparts


plotPoints(xc, yc, x, y);
}
}

// Helper function to plot all 8 symmetric points


private static void plotPoints(int xc, int yc, int x, int y) {
[Link]("(" + (xc + x) + ", " + (yc + y) + ")");
[Link]("(" + (xc - x) + ", " + (yc + y) + ")");
[Link]("(" + (xc + x) + ", " + (yc - y) + ")");
[Link]("(" + (xc - x) + ", " + (yc - y) + ")");
[Link]("(" + (xc + y) + ", " + (yc + x) + ")");
[Link]("(" + (xc - y) + ", " + (yc + x) + ")");
[Link]("(" + (xc + y) + ", " + (yc - x) + ")");
[Link]("(" + (xc - y) + ", " + (yc - x) + ")");
}

public static void main(String[] args) {


int centerX = 50;
int centerY = 50;
int radius = 10;

[Link]("Drawing a circle with center (" + centerX + ",


" + centerY + ") and radius " + radius + ":");
drawCircle(centerX, centerY, radius);
}
}

// Java program for implementing

// Mid-Point Circle Drawing Algorithm

class GFG {

// Implementing Mid-Point Circle

// Drawing Algorithm

static void midPointCircleDraw(int x_centre,

int y_centre, int r)

int x = r, y = 0;
// Printing the initial point

// on the axes after translation

[Link]("(" + (x + x_centre)

+ ", " + (y + y_centre) + ")");

// When radius is zero only a single

// point will be printed

if (r > 0) {

[Link]("(" + (x + x_centre)

+ ", " + (-y + y_centre) + ")");

[Link]("(" + (y + x_centre)

+ ", " + (x + y_centre) + ")");

[Link]("(" + (-y + x_centre)

+ ", " + (x + y_centre) + ")");

// Initialising the value of P

int P = 1 - r;

while (x > y) {

y++;

// Mid-point is inside or on the perimeter

if (P <= 0)

P = P + 2 * y + 1;
// Mid-point is outside the perimeter

else {

x--;

P = P + 2 * y - 2 * x + 1;

// All the perimeter points have already

// been printed

if (x < y)

break;

// Printing the generated point and its

// reflection in the other octants after

// translation

[Link]("(" + (x + x_centre)

+ ", " + (y + y_centre) + ")");

[Link]("(" + (-x + x_centre)

+ ", " + (y + y_centre) + ")");

[Link]("(" + (x + x_centre) +

", " + (-y + y_centre) + ")");

[Link]("(" + (-x + x_centre)

+ ", " + (-y + y_centre) + ")");

// If the generated point is on the

// line x = y then the perimeter points


// have already been printed

if (x != y) {

[Link]("(" + (y + x_centre)

+ ", " + (x + y_centre) + ")");

[Link]("(" + (-y + x_centre)

+ ", " + (x + y_centre) + ")");

[Link]("(" + (y + x_centre)

+ ", " + (-x + y_centre) + ")");

[Link]("(" + (-y + x_centre)

+ ", " + (-x + y_centre) +")");

// Driver code

public static void main(String[] args) {

// To draw a circle of radius

// 3 centered at (0, 0)

midPointCircleDraw(0, 0, 3);

(3, 0) (3, 0) (0, 3) (0, 3)


(3, 1) (-3, 1) (3, -1) (-3, -1)
(1, 3) (-1, 3) (1, -3) (-1, -3)
(2, 2) (-2, 2) (2, -2) (-2, -2)

2D Transformation | Rotation of objects


// Java program to rotate an object by

// a given angle about a given point

public class rotation {

static void rotate(double a[][], int n, int x_pivot,

int y_pivot, int angle)

int i = 0;

while (i < n)

{
// Shifting the pivot point to the origin

// and the given points accordingly

int x_shifted = (int)a[i][0] - x_pivot;

int y_shifted = (int)a[i][1] - y_pivot;

// Calculating the rotated point co-ordinates

// and shifting it back

double x = [Link](angle);

a[i][0] = x_pivot

+ (x_shifted * [Link](x)

- y_shifted * [Link](x));

a[i][1] = y_pivot

+ (x_shifted * [Link](x)

+ y_shifted * [Link](x));

[Link]("(%f, %f) ", a[i][0],

a[i][1]);

i++;

// Driver Code

public static void main(String[] args)

// 1st Example

// The following figure is to be

// rotated about (0, 0) by 90 degrees

int size1 = 4; // No. of vertices

// Vertex co-ordinates must be in order


double points_list1[][] = { { 100, 100 },

{ 150, 200 },

{ 200, 200 },

{ 200, 150 } };

rotate(points_list1, size1, 0, 0, 90);

// 2nd Example

// The following figure is to be

// rotated about (50, -50) by -45 degrees

/*int size2 = 3;//No. of vertices

double points_list2[][2] = {{100, 100}, {100, 200},

{200, 200}};

rotate(points_list2, size2, 50, -50, -45);*/

(-100, 100), (-200, 150), (-200, 200), (-150, 200)

3D Transformation

import [Link].j3d.*;
import [Link].*;

// ... inside a method that sets up the scene


TransformGroup tg = new TransformGroup();
Transform3D transform = new Transform3D();

// Example: Translate and Rotate


Vector3d translation = new Vector3d(0.5, 0.0, 0.0);
[Link](translation);

RotationInterpolator rotator = new RotationInterpolator(


new Alpha(-1, 4000), // Alpha for continuous rotation
tg,
new Transform3D(), // Identity transform for the interpolator
0.0f, (float) [Link] * 2.0f // Rotate 360 degrees
);
BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0),
100.0);
[Link](bounds);
[Link](rotator);

[Link](TransformGroup.ALLOW_TRANSFORM_WRITE);
[Link](transform);

// Add your Shape3D nodes as children of tg


// [Link](yourShape3D)

// Java program to implement Cohen Sutherland algorithm


// for line clipping.
import [Link].*;

class GFG {

// Defining region codes


static final int INSIDE = 0; // 0000
static final int LEFT = 1; // 0001
static final int RIGHT = 2; // 0010
static final int BOTTOM = 4; // 0100
static final int TOP = 8; // 1000

// Defining x_max, y_max and x_min, y_min for


// clipping rectangle. Since diagonal points are
// enough to define a rectangle
static final int x_max = 10;
static final int y_max = 8;
static final int x_min = 4;
static final int y_min = 4;

// Function to compute region code for a point(x, y)


static int computeCode(double x, double y)
{
// initialized as being inside
int code = INSIDE;

if (x < x_min) // to the left of rectangle


code |= LEFT;
else if (x > x_max) // to the right of rectangle
code |= RIGHT;
if (y < y_min) // below the rectangle
code |= BOTTOM;
else if (y > y_max) // above the rectangle
code |= TOP;
return code;
}

// Implementing Cohen-Sutherland algorithm


// Clipping a line from P1 = (x2, y2) to P2 = (x2, y2)
static void cohenSutherlandClip(double x1, double y1,
double x2, double y2)
{
// Compute region codes for P1, P2
int code1 = computeCode(x1, y1);
int code2 = computeCode(x2, y2);

// Initialize line as outside the rectangular window


boolean accept = false;

while (true) {
if ((code1 == 0) && (code2 == 0)) {
// If both endpoints lie within rectangle
accept = true;
break;
}
else if ((code1 & code2) != 0) {
// If both endpoints are outside rectangle,
// in same region
break;
}
else {
// Some segment of line lies within the
// rectangle
int code_out;
double x = 0, y = 0;

// At least one endpoint is outside the


// rectangle, pick it.
if (code1 != 0)
code_out = code1;
else
code_out = code2;

// Find intersection point;


// using formulas y = y1 + slope * (x - x1),
// x = x1 + (1 / slope) * (y - y1)
if ((code_out & TOP) != 0) {
// point is above the clip rectangle
x = x1
+ (x2 - x1) * (y_max - y1)
/ (y2 - y1);
y = y_max;
}
else if ((code_out & BOTTOM) != 0) {
// point is below the rectangle
x = x1
+ (x2 - x1) * (y_min - y1)
/ (y2 - y1);
y = y_min;
}
else if ((code_out & RIGHT) != 0) {
// point is to the right of rectangle
y = y1
+ (y2 - y1) * (x_max - x1)
/ (x2 - x1);
x = x_max;
}
else if ((code_out & LEFT) != 0) {
// point is to the left of rectangle
y = y1
+ (y2 - y1) * (x_min - x1)
/ (x2 - x1);
x = x_min;
}

// Now intersection point x, y is found


// We replace point outside rectangle
// by intersection point
if (code_out == code1) {
x1 = x;
y1 = y;
code1 = computeCode(x1, y1);
}
else {
x2 = x;
y2 = y;
code2 = computeCode(x2, y2);
}
}
}
if (accept) {
[Link]("Line accepted from " + x1
+ ", " + y1 + " to " + x2
+ ", " + y2);
// Here the user can add code to display the
// rectangle along with the accepted (portion
// of) lines
}
else
[Link]("Line rejected");
}

public static void main(String[] args)


{
// First Line segment
// P11 = (5, 5), P12 = (7, 7)
cohenSutherlandClip(5, 5, 7, 7);

// Second Line segment


// P21 = (7, 9), P22 = (11, 4)
cohenSutherlandClip(7, 9, 11, 4);

// Third Line segment


// P31 = (1, 5), P32 = (4, 1)
cohenSutherlandClip(1, 5, 4, 1);
}
}
// This code is contributed by jain_mudit.

import [Link].*;
import [Link].*;
import [Link].*;
import [Link];

public class BezierAnimation extends Applet {


// To give delay for each iteration
void sleep()
{
try {
[Link](100);
repaint();
}
catch (Exception ob) {
}
}

// Paint method
public void paint(Graphics g)
{

// Cubic Beizer Curve Defined by four Control points


// This point's can be change or can be taken from User
int[] x = new int[] { 100, 150, 650, 700 };
int[] y = new int[] { 500, 100, 100, 500 };

// lx and ly store the all x and y co-ordinate generated


// by the first loop to show the path of curve
int[] lx = new int[1200];
int[] ly = new int[1200];

// store the x and y co-ordinate


// of internal lines
int[] xy = new int[10];
double t;
int nx, ny, i = 0;

// Store the calculated x and y


// co-ordinate in lx and ly
for (t = 0.0; t <= 1.0; t += 0.001) {
lx[i] = (int)([Link](1 - t, 3) * x[0] + 3 * t * [Link](1
- t, 2) * x[1] + 3 * t * t * (1 - t) * x[2]
+ [Link](t, 3) * x[3]);
ly[i] = (int)([Link](1 - t, 3) * y[0] + 3 * t * [Link](1
- t, 2) * y[1] + 3 * t * t * (1 - t) * y[2]
+ [Link](t, 3) * y[3]);
i++;
}

// display all the lines Curve and animation


for (t = 0.0; t <= 1.0; t += 0.01) {
nx = (int)([Link](1 - t, 3) * x[0] + 3 * t * [Link](1 -
t, 2) * x[1] + 3 * t * t * (1 - t) * x[2]
+ [Link](t, 3) * x[3]);
ny = (int)([Link](1 - t, 3) * y[0] + 3 * t * [Link](1 -
t, 2) * y[1] + 3 * t * t * (1 - t) * y[2]
+ [Link](t, 3) * y[3]);

// calculating the x and y for displaying the


// internal line form in bezier curve
xy[0] = (int)((1 - t) * x[0] + t * x[1]);
xy[1] = (int)((1 - t) * y[0] + t * y[1]);
xy[2] = (int)((1 - t) * x[1] + t * x[2]);
xy[3] = (int)((1 - t) * y[1] + t * y[2]);
xy[4] = (int)((1 - t) * x[2] + t * x[3]);
xy[5] = (int)((1 - t) * y[2] + t * y[3]);
xy[6] = (int)((1 - t) * xy[0] + t * xy[2]);
xy[7] = (int)((1 - t) * xy[1] + t * xy[3]);
xy[8] = (int)((1 - t) * xy[2] + t * xy[4]);
xy[9] = (int)((1 - t) * xy[3] + t * xy[5]);
[Link]([Link]);

// Outline for the bezier curve


[Link](x[0], y[0], x[1], y[1]);
[Link](x[1], y[1], x[2], y[2]);
[Link](x[2], y[2], x[3], y[3]);

// making a big dot at each control point


[Link](x[0] - 5, y[0] - 5, 10, 10);
[Link](x[1] - 5, y[1] - 5, 10, 10);
[Link](x[2] - 5, y[2] - 5, 10, 10);
[Link](x[3] - 5, y[3] - 5, 10, 10);
[Link]([Link]);

// Show Trace of the curve


[Link](nx - 5, ny, nx + 5, ny);
[Link](nx, ny - 5, nx, ny + 5);
[Link](lx, ly, i);
[Link]([Link]);
[Link](xy[0], xy[1], xy[2], xy[3]);
[Link](xy[2], xy[3], xy[4], xy[5]);
[Link](xy[6], xy[7], xy[8], xy[9]);

// Labeling the Control points


[Link]("A", x[0] + 5, y[0] - 5);
[Link]("B", x[1] + 5, y[1] - 5);
[Link]("C", x[2] + 5, y[2] - 5);
[Link]("D", x[3] + 5, y[3] - 5);

// Labeling the interal moving line


[Link]("AB", xy[0] + 5, xy[1] - 5);
[Link]("BC", xy[2] + 5, xy[3] - 5);
[Link]("CD", xy[4] + 5, xy[5] - 5);
[Link]("ABC", xy[6] + 5, xy[7] - 5);
[Link]("BCD", xy[8] + 5, xy[9] - 5);

// making the end of line bold


[Link](xy[0] - 4, xy[1] - 4, 8, 8);
[Link](xy[2] - 4, xy[3] - 4, 8, 8);
[Link](xy[4] - 4, xy[5] - 4, 8, 8);
[Link](xy[6] - 4, xy[7] - 4, 8, 8);
[Link](xy[8] - 4, xy[9] - 4, 8, 8);

// Gives delay and paint the


// screen white for next iteration
sleep();
[Link]([Link]);
[Link](0, 0, 1000, 1000);
}
}
// Main Method
// if This method raise any error Remove the Main method
public static void main(String[] args)
{
BezierAnimation a = new BezierAnimation();
JFrame jp1 = new JFrame();
[Link]().add(a, [Link]);
[Link](new Dimension(1000, 1000));
[Link](true);
}
}

Common questions

Powered by AI

Bresenham's circle drawing algorithm is known for its efficiency in integer-based calculations, which avoids floating-point arithmetic and uses only additions and subtractions to determine the positions of the symmetric points. It updates the decision parameter iteratively to plot the symmetric points efficiently . Meanwhile, the Midpoint circle algorithm also avoids floating-point arithmetic and instead focuses on minimizing absolute error, maintaining a decision parameter to choose between pixels based on their position relative to the circle's perimeter . Although both algorithms avoid floating-point calculations, Bresenham's method is favored for its simplicity and speed in typical implementations as it uses simpler arithmetic operations and conditions.

A Bezier curve is plotted using a set of control points, typically involving calculations that blend these points to form the curve. The control points determine the direction and curvature of the path. By iterating the parameter 't' from 0 to 1, and using the polynomial equations of Bezier curves, the coordinates for points on the curve are computed. Each calculated point on the Bezier curve is a weighted sum of the control points, where the weights are determined by Bernstein polynomials . Adjusting the control points changes the weights and the overall shape of the curve, allowing designers to create complex and smooth paths that are essential in graphical modeling and animation.

Rotating a 2D object about a non-origin point involves translating the object such that the pivot point aligns with the origin, applying the rotation matrix transformation, and translating it back to its original location. This series of transformations includes calculating rotational angles and using trigonometric functions to determine new coordinates based on angular displacement . Challenges include maintaining the object's orientation and scale, computational accuracy over multiple coordinate transformations, and managing graphical artifacts or misalignments in complex scenes, which require precise arithmetic operations and potentially added computational load.

Symmetric points generation in circle plotting algorithms, such as Bresenham's and Midpoint, take advantage of a circle's geometric properties. Since a circle is symmetric, computing points on one octant allows the calculation of corresponding points across the entire circle. This reduces computational effort significantly because the algorithm only needs to solve the circle equation for one segment (1/8th) of the circle and mirror these points to the other segments . This symmetry reduces redundancy, minimizes calculations, and accelerates processing, making these algorithms very efficient for rendering circles in pixel-based graphical systems.

The parameter 't' in Bezier curve plotting is a normalized value that determines the interpolation along the curve between control points. Iterative control of 't' affects both the visualization and accuracy of the curve by defining the resolution and smoothness of the rendered path. By increasing the number of iterations or the granularity of 't', more points are plotted, resulting in a smoother, more accurate representation of the intended Bezier curve . However, finer divisions of 't' demand increased processing power and memory, potentially impacting performance in real-time graphics applications.

Bezier curves provide a more flexible and smooth path for animations due to their ability to easily control the trajectory with control points, unlike simple linear interpolation that creates direct, linear trajectories without curve flexibility. Bezier curves can create complex, flowing motion paths by adjusting control points, leading to natural-looking animations as seen in character animations or smooth graphic transitions . In contrast, linear interpolation tends to produce rigid, mechanical movements because it only interpolates between two points without any smooth transitional pattern, making it less ideal for intricate animations requiring organic motion.

In the Midpoint Circle Algorithm, the decision parameter dictates whether the midpoint between two consecutive potential pixels lies inside or outside the circle. It helps decide which pixel closest to the circle's edge should be selected for plotting. By adjusting this parameter iteratively, the algorithm can extend the circle incrementally while ensuring that each plotted point maintains symmetry .

Rotating graphical objects around a pivot point requires translating the object to the origin, applying the rotation transformation, and translating it back to the pivot's position. This involves transforming each vertex of the object using rotation matrices, which are usually coordinate space-dependent . The implications include changes in orientation that affect visual appearance or interpretation from certain perspectives. Coordinate space transformation might necessitate recalculation of positions for consistent results, as differing spaces can result in misalignments or unexpected positions in composite scenes. Correctly handling these transformations ensures visual fidelity, alignment with other objects, and accurate representation within a virtual environment.

In the Cohen-Sutherland algorithm, endpoint clipping is handled using a region code that helps in determining which endpoints are outside the clipping rectangle. Steps involved include examining each endpoint's region code to decide its location relative to the rectangle (above, below, left, or right). If a line segment's endpoints are within the rectangle, it's immediately accepted. If not, the algorithm selectively clips the endpoints by computing intersections with the rectangle edges using slope-intercept calculations . The process is iterative, continuously updating each endpoint's code until either the line is fully accepted, fully rejected, or split appropriately. This approach ensures precise calculation of any visible segment within the clipping region.

The Cohen-Sutherland algorithm efficiently determines intersection points by using a region code outcode method, allowing it to quickly decide the position of the points relative to the clipping region. This is particularly advantageous because it can trivially reject or accept a line segment based on precomputed region codes without performing complex calculations . Compared to other clipping algorithms like the Liang-Barsky algorithm, Cohen-Sutherland is generally easier to implement and understand, though it may be less optimal in terms of computational efficiency since it potentially examines more trivial cases. Its primary advantage is its ability to determine intersections with a systematic approach using bitwise operations to categorize the endpoints.

You might also like