java image draw

Solutions on MaxInterview for java image draw by the best coders in the world

showing results for - "java image draw"
Chiara
07 Nov 2019
1package com.javacodegeeks.snippets.desktop;
2 
3import java.awt.Component;
4import java.awt.Frame;
5import java.awt.Graphics;
6import java.awt.Graphics2D;
7import java.awt.Image;
8import java.awt.Toolkit;
9 
10public class DrawImage {
11 
12  static Image image;
13 
14  public static void main(String[] args) {
15 
16// The image URL - change to where your image file is located!
17 
18String imageURL = "image.png";
19 
20// This call returns immediately and pixels are loaded in the background
21 
22image = Toolkit.getDefaultToolkit().getImage(imageURL);
23 
24// Create a frame
25 
26Frame frame = new Frame();
27 
28// Add a component with a custom paint method
29 
30frame.add(new CustomPaintComponent());
31 
32// Display the frame
33 
34int frameWidth = 300;
35 
36int frameHeight = 300;
37 
38frame.setSize(frameWidth, frameHeight);
39 
40frame.setVisible(true);
41 
42 }
43 
44 /**
45  * To draw on the screen, it is first necessary to subclass a Component 
46  * and override its paint() method. The paint() method is automatically called 
47  * by the windowing system whenever component's area needs to be repainted.
48  */
49  static class CustomPaintComponent extends Component {
50 
51public void paint(Graphics g) {
52 
53  // Retrieve the graphics context; this object is used to paint shapes
54 
55  Graphics2D g2d = (Graphics2D)g;
56 
57  /**
58   * Draw an Image object
59   * The coordinate system of a graphics context is such that the origin is at the 
60   * northwest corner and x-axis increases toward the right while the y-axis increases 
61   * toward the bottom.
62   */
63 
64  int x = 0;
65 
66  int y = 0;
67 
68  g2d.drawImage(image, x, y, this);
69 
70}
71 
72  }
73 
74}
75