Painting on canvas in native cocoa

Hi Friends,
I need a make a java canvas in which i have to paint thumbnail images by native cocoa code.
I had got drawing surface(ds) and drawing surface interface(dsi).Also i am able to read the thumbnail images but donot know how to paint images in canvas using cocoa.
Please suggest and if possible give some example or code sample.
Thanks in advance.

the bare minimum to render to a fullscreen frame in the fastest way possible...
Frame f = new Frame();
f.getGraphicsConfiguration().getDefaultDevice().setFullScreenWindow(f);
f.createBufferStrategy(2);
BufferStrategy bs = f.getBufferStrategy();
Random r = new Random();
while(true)
   Graphics g = bs.getDrawGraphics();
   g.setColor(new Color(r.nextInt));
   g.fillRect(0,0,getWidth(),getHeight());
   g.dispose();
   bs.show();
}

Similar Messages

  • Python and PyObjC, developing native Cocoa apps rapidly!

    Python is all grown up it seems for developing native OS X applications. For those who want to check out how to rapidly put together native Cocoa apps in less than half the lines of code and none of the manual memory management of the C derivative languages, Apple now has some articles on the developer site to inspire and to help point the way.
    Although my personal preference is wxPython for making GUI's that will look like native Windows/OSX/Unix applications no matter what platform the python app is run on I still will give PyObjC a go.
    wxPython - http://www.wxpython.org/
    MacPython - http://wiki.python.org/moin/MacPython/
    Using PyObjC - http://developer.apple.com/cocoa/pyobjc.html
    Python/PyObjC Inspiration - http://developer.apple.com/business/macmarket/checkout.html
    Mac Mini (Home), Dell Laptop [removed Windows, installed Ubuntu Linux] (Work)   Mac OS X (10.4.10)   badvista.fsf.org

    Note: Fixed omission of link to checkout
    Quicktime Tour of the Python/PyObjC Application in action:
    http://www.checkoutapp.com/show/quicktours#

  • How to Achieve Oil Painting on Canvas Effect?

    A friend took a picture of an portrait of her grandfather painted in oil on canvas.  She has asked me to "Photoshop" the picture so that the canvas effect shows up in the picture.  I use PSE 8 in Win 7.  Thanks.

    Filter>Texture>Texturizer>Canvas. However, you may need to play with this to make it large enough to show in a print, if that's your intended output.
    You might also try loading a burlap texture, which may give a more visible woven effect.

  • Won't paint to canvas

    Hi,
    I know this is a bit of a chunk of code but it is all beginner stuff. I posted earlier on this. It won't paint with the to the canvas.
    Any help very much appreciated.
    Warby
    package Stejava;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    /** An example class used to demonstrate the basics of
    * creating components such as panels, arranging
    * components using layout objects, and nesting
    * components inside each other.
    public class Assignment_2 extends JFrame
         JMenuBar menuBar;
         JMenu menu;
         JMenuItem menuItem;
         public JPanel grid, gridBag, flow, outputScreen, optionsBox, message, baseButtons,
              another, centreOne, centreTwo, centreThree, lower, style, size, colours, shapes,
              menuPane;
         JRadioButtonMenuItem rbMenuItem1, rbMenuItem2;
         public JTextField text;
         public JButton black, red, green;
         public JCheckBox checkStyle;
         /** Class constructor method
              * @param titleText Window's title bar text
         public Assignment_2( String titleText ) // constructor
              super( titleText );
              // listener for close event
              addWindowListener( new WindowAdapter() {
              /** End the program when the user
    * closes the window
    public void
    windowClosing( WindowEvent e )
    Assignment_2.this.dispose();
    System.exit( 0 );
                   }// end windowclosing()
              }// end WindowAdaptor()
              // end parameter listing of addWindowListener(). No code it seems.
              // menu bar
              menuBar = new JMenuBar();
    setJMenuBar(menuBar);
              //Build the first menu.
    menu = new JMenu("A Menu");
    menuBar.add(menu);
              //a group of JMenuItems
    menuItem = new JMenuItem("none" );
              menu.add(menuItem);
    menuItem = new JMenuItem("Point" );
              menu.add(menuItem);
              menuItem = new JMenuItem("Line" );
              menu.add(menuItem);
              menuItem = new JMenuItem("Triangle" );
              menu.add(menuItem);
              menuItem = new JMenuItem("Square" );
              menu.add(menuItem);
              menuItem = new JMenuItem("Circle" );
              menu.add(menuItem);
              menuItem = new JMenuItem("Oval" );
              menu.add(menuItem);
              menuItem = new JMenuItem("Text" );
              menu.add(menuItem);
              outputScreen = new JPanel();
              outputScreen.setSize(300,240);
              outputScreen.setMinimumSize(new Dimension(300, 200) );
              outputScreen.setPreferredSize( new Dimension(300, 200 ));
              outputScreen.setBorder(BorderFactory.createTitledBorder( "Output" ) );
              outputScreen.setLayout( new BorderLayout() );
              style = new JPanel();
              style.setBorder(BorderFactory.createTitledBorder( "Style" ) );
              style.setLayout( new GridLayout( 0, 1 ) );
              style.add( new JCheckBox( "Bold" ) );
              style.add( new JCheckBox( "Italics" ) );
              size = new JPanel();
              size.setBorder(BorderFactory.createTitledBorder( "Size" ) );
              size.setLayout( new BoxLayout( size, BoxLayout.Y_AXIS));
              size.setMinimumSize(new Dimension(100, 100) );
              size.setPreferredSize( new Dimension(100, 100 ));
              menuPane = new JPanel();
              menuPane.setBorder(BorderFactory.createTitledBorder( "" ) );
              menuPane.setMinimumSize( new Dimension(250, 400));
              menuPane.setLayout( new BorderLayout() );
              menuPane.add( menuBar );
              centreOne = new JPanel();
              centreOne.setBorder(BorderFactory.createTitledBorder( "Text Options" ) );
              centreOne.setLayout( new GridLayout( 0, 1 ) );
              centreOne.setMinimumSize(new Dimension(100, 220) );
              centreOne.setPreferredSize( new Dimension(100, 220 ));
              centreOne.add( style );
              centreOne.add( size );
              centreTwo = new JPanel();
              centreTwo.setBorder(BorderFactory.createTitledBorder( "Colours" ) );
              centreTwo.setLayout( new GridLayout( 0, 1 ) );
              centreTwo.setMinimumSize(new Dimension(100, 220) );
              centreTwo.setPreferredSize( new Dimension(100, 220 ));
              //centreTwo.add ( colours );
              centreThree = new JPanel();
              centreThree.setBorder(BorderFactory.createTitledBorder( "Shapes" ) );
              centreThree.setLayout( new BorderLayout() );
              centreThree.setPreferredSize( new Dimension(100, 220 ));
              centreThree.setMinimumSize( new Dimension(100, 220));
              centreThree.add ( menuPane );
              optionsBox = new JPanel();
         //optionsBox.setLayout( new BorderLayout() );
              optionsBox.setPreferredSize( new Dimension(300, 220 ));
              optionsBox.setMinimumSize( new Dimension(300, 220));
              optionsBox.setSize ( 300, 220 );
              optionsBox.add ( centreOne );
              optionsBox.add ( centreTwo );
              optionsBox.add ( centreThree );
              lower = new JPanel();
              lower.setBorder(BorderFactory.createTitledBorder( "" ) );
              lower.setMinimumSize( new Dimension(250, 400));
              lower.setLayout( new GridLayout( 0, 1 ) );
              message = new JPanel();
              message.setBorder(BorderFactory.createTitledBorder("Message" ) );
              message.setLayout( new BorderLayout() );
              text = new JTextField( "hhhh" );
              message.add( text, BorderLayout.CENTER );
              //button bar and buttons
              baseButtons = new JPanel();
              baseButtons.setBorder( BorderFactory.createTitledBorder( "" ) );
              baseButtons.setLayout( new FlowLayout( FlowLayout.CENTER ) );
              black = new JButton( "About" );
              black.addActionListener( new ButtonListener( Color.black ) );
              baseButtons.add( black );
              red = new JButton( "Draw" );
              red.addActionListener( new ButtonListener( Color.red ) );
              baseButtons.add( red );
              green = new JButton( "Exit" );
              green.addActionListener(new ButtonListener( Color.green ) );
              baseButtons.add( green );
              // radio buttons for text size
              menu.addSeparator();
    ButtonGroup group1 = new ButtonGroup();
              size.setLayout( new GridLayout( 0, 1 ) );
              rbMenuItem1 = new JRadioButtonMenuItem("Small");
    group1.add(rbMenuItem1);
    size.add(rbMenuItem1);
    rbMenuItem1 = new JRadioButtonMenuItem("Medium");
    group1.add(rbMenuItem1);
    size.add(rbMenuItem1);
              rbMenuItem1 = new JRadioButtonMenuItem("Large");
    group1.add(rbMenuItem1);
    size.add(rbMenuItem1);
              // radio buttons
              menu.addSeparator();
    ButtonGroup group2 = new ButtonGroup();
              //size.setLayout( new FlowLayout( FlowLayout.CENTER ) );
              rbMenuItem2 = new JRadioButtonMenuItem("Black");
    group2.add(rbMenuItem2);
    centreTwo.add(rbMenuItem2);
    rbMenuItem2 = new JRadioButtonMenuItem("Red");
    group2.add(rbMenuItem2);
    centreTwo.add(rbMenuItem2);
              rbMenuItem2 = new JRadioButtonMenuItem("Orange");
    group2.add(rbMenuItem2);
    centreTwo.add(rbMenuItem2);
              rbMenuItem2 = new JRadioButtonMenuItem("Yellow");
    group2.add(rbMenuItem2);
    centreTwo.add(rbMenuItem2);
    rbMenuItem2 = new JRadioButtonMenuItem("Green");
    group2.add(rbMenuItem2);
    centreTwo.add(rbMenuItem2);
              rbMenuItem2 = new JRadioButtonMenuItem("Blue");
    group2.add(rbMenuItem2);
    centreTwo.add(rbMenuItem2);
              //aCanvas.repaint();
              //aCanvas.setSize( 100, 100 );
              //aCanvas.setVisible( true );
              //aCanvas.setLayout( new GridLayout( 0, 1 ) );
              //aCanvas.setMinimumSize(new Dimension(100, 100) );
              //aCanvas.setPreferredSize( new Dimension(100, 100 ));
              // container     
              Container cp = getContentPane();
              cp.setLayout( new BorderLayout() );
              cp.add( outputScreen, BorderLayout.NORTH );
              cp.add( optionsBox, BorderLayout.CENTER );
              cp.add( lower, BorderLayout.SOUTH );
              lower.add( message );
              lower.add( baseButtons );
              pack();
              setSize (350, 580);
              setResizable( false );
              setVisible( true );
              outputScreen.add( new myCanvas() );
         }// ends what ??? Constructor???
                        //inner class for painting
         class myCanvas extends Canvas
              /** Class constructor
                   public myCanvas()
                        repaint();
                        setBackground( Color.white );
                        //setBorder( BorderFactory.createTitledBorder( "Sample output from drawing methods:" ) );
                   }// end paint constructor
              public void paint(Graphics g)
                   super.paint(g); // clears background
                   g.drawLine( 50, 50, 100, 200 );
                   g.setColor( Color.blue );
                   g.drawRoundRect( 150, 300, 100, 125, 15, 15 );
                   g.setColor( Color.red );
                   g.fillOval( 400, 200, 50, 180 );
              }// end method paint()     
         } // end myClass;
              //myCanvas aCanvas = new myCanvas();
    /** The class representing the button event
    * listeners
    class ButtonListener implements ActionListener
         public Color c;
    /** Class constructor
    * @param c the color for this button
    public ButtonListener( Color c )
    this.c = c;
    /** Respond to the action events
    * @param e The click event
    public void actionPerformed( ActionEvent e )
    text.setForeground( c );
              outputScreen.repaint(7);
              //outputScreen.aCanvas.paint();
    }// end class ButtonListener()
    /** The class representing the colored icons on
    * the buttons
    class ColorIcon implements Icon
    public Color c;
    public static final int DIAMETER = 10;
    /** Class constructor
    * @param c the color for this button
    public ColorIcon( Color c )
    this.c = c;
    /** Paint the color icon with a black border
    * @param cp the component holding the icon
    * @param g the graphics context for the icon
    * @param x the x draw start position
    * @param y the y draw start position
    public void paintIcon( Component cp, Graphics g, int x, int y )
    g.setColor( c );
    g.fillOval( x, y, DIAMETER, DIAMETER );
    g.setColor( Color.black );
    g.drawOval( x, y, DIAMETER, DIAMETER );
    /** Get the icon's height
    * @return the height of the icon
    public int getIconHeight()
    return DIAMETER;
    /** Get the icon's width
    * @return the width of the icon
    public int getIconWidth()
    return DIAMETER;
    }// end class colorIcon
    }// end colorIcon
    /** The test method for the class
    * @param args not used
    public static void main( String[] args )
    new Assignment_2( "Assignment_2" );
    }// end class Assignment_2

    No, does not look correct.
    Canvas is a "heavyweight" awt component.
    It is generally a bad idea to mix these with the "lightweight" swing JComponents.
    Forget that and let's move on
    Paint directly on the JPanel
    example(strech and maximize to see what happens):import javax.swing.*;
    import java.awt.*;
    public class Test extends JFrame
       public Test()
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          setSize(100,100);
          OutputScreen oScr = new OutputScreen();
          getContentPane().add(oScr, BorderLayout.CENTER);
          oScr.setToolTipText("<html>Test<br>Patern</html>");
       public static void main(String[] args)
              new Test().setVisible(true);
    class OutputScreen extends JPanel
       public void paint(Graphics g)
          Rectangle r = getBounds();
          g.setColor(Color.white);
          g.clearRect(r.x, r.y, r.width, r.height);
          g.setColor(Color.red);
          g.fillOval(r.x, r.y, r.width, r.height);
    }

  • Painting on Canvas or Applet?

    1) I have been writing an RPG for some time using j2sdk1.4.1_01 in windowsxp, The main component I'm drawing on is now a Canvas but was originally an Applet, Which is a better choice to use? I am using a double buffering system with VolatileImage and Fullscreen Exclusive mode with a Frame at 640x480 screen size. I have set the framerate to repaint at 25 fps. 2) Any performance boosting suggestions?

    the bare minimum to render to a fullscreen frame in the fastest way possible...
    Frame f = new Frame();
    f.getGraphicsConfiguration().getDefaultDevice().setFullScreenWindow(f);
    f.createBufferStrategy(2);
    BufferStrategy bs = f.getBufferStrategy();
    Random r = new Random();
    while(true)
       Graphics g = bs.getDrawGraphics();
       g.setColor(new Color(r.nextInt));
       g.fillRect(0,0,getWidth(),getHeight());
       g.dispose();
       bs.show();
    }

  • Image drawing in cocoa

    Hi Friends,
    I need a make a java canvas in which i have to paint thumbnail images by native cocoa code.
    I had got drawing surface(ds) and drawing surface interface(dsi).Also i am able to read the thumbnail images but donot know how to paint images in canvas.
    Please suggest and if possible give some example or code sample.
    Thanks in advance.

    Welcome to Apple Discussions, Vinod!
    You have asked your question in a forum devoted to questions about Apple Discussions themselves. You are much more likely to get an answer in the "Developer" forum:
    http://discussions.apple.com/thread.jspa?threadID=1064635&tstart=0

  • Native Canvas Painting and Refresh

    Hi,
    I have a project where I get live video from a firewire camera, and paint it to an awt Canvas natively using JNI. I need additional items painted on the canvas (on top of the video), like a pair of crosshairs and rulers to measure certain widths, etc. The software tracks an object moving across the screen, so the crosshairs need to be moved around and refreshed often.
    I am getting a strange problem - the natively painted video is working just fine, but the painted objects are not refreshing properly. For example, instead of getting a crosshair that moves around the screen, I get a trail of crosshairs. And underneath the crosshairs, the video is refreshing just fine. What's going on? I'm using libXv, an X-windows extension to paint YUV4:2:2 camera buffers directly to the screen.
    Here are relevant class snippets:
    public class NativeCanvas extends Canvas{
        public void update(Graphics g)                 <-- overridden to eliminate flicker
            paint(g);
        public native void paint(Graphics g);         <-- here's the native video drawing function
    public class CanvasWithOverlays extends NativeCanvas
        public void paint(Graphics g)
               super.paint();
               Graphics2D g2 = (Graphics2D)g;
               //(paint crosshairs, etc)
    } Any help will be greatly appreciated. Thanks very much!
    --Ismail Degani
    High Energy Synchrotron Source
    Cornell University

    Hi,
    I'm not sure how the crosshairs can be out of sync with the video stream - the canvas paint routines paint the video frame natively, and then paint the crosshairs. It's all sequential -
    super.paint();    // goes into a native function XvPutImage that quickly blits the frame on screen
    Graphics2D g2 = (Graphics2D)g;          
    //(paint crosshairs, etc) This should work properly with the Event Queue, to the best of my knowledge. I schedule a TimerTask that continually calls the repaint() method to refresh the video:
    public class LiveVideoPainter extends TimerTask
        static Logger logger = Logger.getLogger(LiveVideoPainter.class.getName());
        NativeCanvas nc;
        VideoDataSource vs;
        public LiveVideoPainter(NativeCanvas nc, VideoDataSource vs)
            if(nc == null)  {
                logger.error("The Native Canvas is null!");
                return;
            if(vs == null)  {
                logger.error("The Video Data Source is null!");
                return;
            this.nc = nc;
            this.vs = vs;
        public void run()
            vs.getFrame(nc.buffer);
            nc.repaint();
    } I actually had this same problem when designing this application with C++ using the Qt windowing toolkit a year ago. Basically, if I called XvPutimage, and then called regular X drawing routines like XDrawLine etc in a loop, it would draw successfully, but never refresh properly:
    while(true)
    get_decompressed_frame(buf);
    xv_image=XvCreateImage(display,info[0].base_id, XV_UYVY, (char*)buf, 1024, 768);
    XvPutImage(display, info[0].base_id, window, gc, xv_image,
                       0,0,1024,768,
                       0,0, 1024,768);
    if(crossHairDisplayed)
    // Draw Horizontal CrossHair                                                                                                                                                           
                XDrawLine(display, window, gc,
                          0,   (int)(DataSource::pixPerMicron*DataSource :: crossY + DataSource::zcenY),
                          1024,(int)(DataSource::pixPerMicron*DataSource :: crossY + DataSource::zcenY));
                // Draw Vertical CrossHair                                                                                                                                                             
                XDrawLine(display, window, gc,
                          (int)(DataSource::pixPerMicron*DataSource :: crossX + DataSource::zcenX), 0,
                          (int)(DataSource::pixPerMicron*DataSource :: crossX + DataSource::zcenX) , 768);
    }In this code bit, the crosshairs should move when the DataSource object changes member variables, line CrossX. But, the old crosshairs would not go away until the window was moved or resized. I'd get two crosshairs on the screen. I had to use a hack from the xwindows utility xrefresh everytime the crosshairs changed. It essentially simulated an x-window that opened over the Qt window, and then immediately closed. This worked well, but I thought I'd be free of that hack when I moved to java and JNI. Isn't this bizarre? Why would the window hold on to the old crosshair even when the varialbes change and there isn't any code that repaints it there after the video frame gets blitted?
    hack adapted from xrefresh.c:
          if(newCrossHair)
                              Visual visual;
                      XSetWindowAttributes xswa;
                      Display *dpy;
                      unsigned long mask = 0;
                      int screen;
                      Window win;
                      if ((dpy = XOpenDisplay(NULL)) == NULL) {
                        fprintf (stderr, "unable to open display\n");
                        return;
                      screen = DefaultScreen (dpy);
                      xswa.background_pixmap = ParentRelative;
                      mask |= CWBackPixmap;
                      xswa.override_redirect = True;
                      xswa.backing_store = NotUseful;
                      xswa.save_under = False;
                      mask |= (CWOverrideRedirect | CWBackingStore | CWSaveUnder);
                      visual.visualid = CopyFromParent;
                      win = XCreateWindow(dpy, DefaultRootWindow(dpy), 400, 600, 1, 1,
                                          0, DefaultDepth(dpy, screen), InputOutput, &visual, mask, &xswa);
                      XMapWindow (dpy, win);
                      /* the following will free the color that we might have allocateded */
                      XCloseDisplay (dpy);
                      newCrossHair = false;
          } Any ideas? There's probably just some type of refresh call I need to use.
    --Ismail                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Convert photo to oil on canvas?

    Is there a way to do this? I've played around with some of the filters and stuff - artistic, sketch, water colors, etc - as well as some of the background layer options in some of these filters as well. I'm just not that familiar with how they all work and what they're meant to do.
    What I want to do is to convert a family photo to look like it was given the 'painted on canvas' look that some professional studios offer - such as for senior pictures or family portraits and the like. Suitable for framing in other words.
    Is there anyone familiar with that process and how it might be done in a few PSE 3 steps?
    Thanks,
    Dennis

    Dennis,
    You can get the canvas texture part of your request by clicking Filter >
    Texture > Texturizer...
    Select Canvas from the Texture drop-down, and adjust the other parameters to
    your preference. If you don't like the outcome, just Undo and try again
    with different settings.
    As far as the oil part of your request - someone else will need to advise,
    as I have no eye for that sort of thing.
    HTH,
    Byron

  • How to smooth lines of original oil painting

    I had an artist paint an oil painting (on canvas) of our wedding venue to use as part of our wedding invitation. However, I didn't realize how an oil painting would print on paper and the brush strokes are nonuniform and visible. How can I smooth out the brush strokes?

    50mm will be fine.  I expect its sweet spot will be around f8
    Align the lens axis with the center of the image and perpendicular to the image.
    If the sun is bright, find some shade.  In fact find some shade anyway.
    Use a tripod
    Take a test image with a sheet of white paper in front to the painting to set white balance to in Photoshop. But try to take the image well away from any brightly coloured surfaces that might reflect colour onto the painting.
    DO NOT USE FLASH
    Try and leave an inch or two of space around the painting.  This will help you square it up in Photoshop
    Later versions of Photoshop have a Perspective Crop tool that would let you correct any out of squareness of the photograph, but you can still do this with CS5
    Open the image, and make any adjustments like black and white point.
    Copy the background layer.
    Turn on the grid (Ctrl ')
    Free Transform (Ctrl t)
    Hold down the Ctrl key, and drag each corner in turn to align the edges to the grid to square it up.
    Crop out what is left.
    Sharpen for print (View at 60% and go by the preview)
    Be amazed by how much better it looks compared to the scanned version
    Have a great special day, and best wishes to your SO
    Now that's definitely me for today. (12.39am and I NEED my sleep)

  • Change origin of canvas

    hey, i have a canvas that positions itself in the middle of the screen with two lines (x and y axis). the problem is that i want to be able to move the origin, which then draws the axis again.
    thanks
    Pedge
    // GCanvas.java
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    * This class extends the canvas class to include the input and drawing of a polygon
    * @author Geoff Hobson
    * @version 1.1 (24 Nov 99)
    class GCanvas extends Canvas
    * the polygon object associated with this canvas.
    private GPolygon polygon;
    * indicates whether currently in process of colecting the vertices of a polygon.
    private boolean building = false;
    * the size of one pixel in the logical coordinates of the polygon - the scaling factor.
    float pixelSize;
    * the screen x coordinate of the logical origin - screen x position of y-axis.
    int centerX;
    * the screen y coordinate of the logical origin - screen y position of x-axis.
    int centerY;
    * the radius of the circle around the start point,
    * a mouse press anywhere in this circle will be treated as selecting the centre point.
    private int circleSize = 3;
    * Constructs a GCanvas and associates it with the given Polygon poly.
    * @param poly the polygon object which is to be drawn and manipulated
    GCanvas(GPolygon poly)
    polygon = poly;
    addMouseListener
    (new MouseAdapter()
    { public void mousePressed(MouseEvent evt)
    pointSelected(evt.getX(), evt.getY());
    ); // end of new MouseAdapter
    setBackground(Color.gray);
    private int cX, cY;
    * clears the canvas and sets it ready for the input of a new polygon.
    public void newPoly()
    building = true;
    setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
    repaint();
    * The action to be performed when a point is selected by a mouse press.
    * @param x the x coordinate of the selected point
    * @param y the y coordinate of the selected point
    private void pointSelected(int x, int y)
    if (building)
    addVertex(x, y);
    * Add a new vertex to the polygon object
    * @param x the x coordinate of the new vertex
    * @param y the y coordinate of the new vertex
    private void addVertex(int x, int y)
    if (polygon.size() == 0)
    polygon.addVertex(new Point2D(fX(x), fY(y))); // add first vertex to a polygon
    else
    Point2D v0 = polygon.getVertex(0);
    int dx = x - iX(v0.x), dy = y - iY(v0.y);
    if (dx * dx + dy * dy < circleSize * circleSize)
    {    // mouse in circle around first vertex
    polygon.closePolygon(); // the polygon has been closed
    building = false;
    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    else
    polygon.addVertex(new Point2D(fX(x), fY(y))); // add an other vertex to polygon
    repaint();
    * Converts logical to screen x coordinate
    * @param x the logical x coordinate
    * @return the screen x coordinate
    int iX(float x)
    return Math.round(centerX + x/pixelSize);
    * Converts logical to screen y coordinate
    * @param x the logical y coordinate
    * @return the screen y coordinate
    int iY(float y)
    return Math.round(centerY - y/pixelSize);
    * Converts screen to logical x coordinate
    * @param x the screen x coordinate
    * @return the logical x coordinate
    float fX(int x)
    return (x - centerX) * pixelSize;
    * Converts screen to logical y coordinate
    * @param x the screen y coordinate
    * @return the logical y coordinate
    float fY(int y)
    return (centerY - y) * pixelSize;
    * Paints the canvas with current state of polygon
    * @param g the graphic context for the paint method
    public void paint(Graphics g)
    // initialise a blank canvas and draw axes etc
    int maxX = getSize().width - 1; // get size of screen
    int maxY = getSize().height - 1;
    float rWidth = polygon.logicalWidth(); // get logical size of polygon
    float rHeight = polygon.logicalHeight();
    pixelSize = Math.max(rWidth/maxX, rHeight/maxY); // calculate scaling factor
    centerX = maxX/2; // calculate position of axes
    centerY = maxY/2;
    int left = iX(-rWidth/2); // calculate edges of logical polygon
    int right = iX(rWidth/2);
    int bottom = iY(-rHeight/2);
    int top = iY(rHeight/2);
    // draw white rectangle for logical polygon
    g.setColor(Color.white);
    g.fillRect(left, top, right - left+1, bottom - top+1);
    // draw frame around logical polygon rectangle
    g.setColor(Color.darkGray);
    g.drawRect(left, top, right - left, bottom - top);
    g.setColor(Color.lightGray);
    g.drawLine(left,centerY, right,centerY); // draw x axis
    g.drawLine(centerX,top, centerX,bottom); // draw y-axis
    // draw current state of the polygon
    int n = polygon.size();
    if (n == 0) return; // if there are no vertices
    Point2D A, B;
    A = (polygon.getVertex(0));
    // Show tiny circle around first vertex:
    g.setColor(Color.red);
    if (!polygon.isClosed())
    g.drawOval(iX(A.x)-circleSize, iY(A.y)-circleSize, circleSize*2, circleSize*2);
    // draw the polygon
    g.setColor(Color.blue);
    for (int i=1; i<n; i++)
    B = (polygon.getVertex(i));
    g.drawLine(iX(A.x), iY(A.y), iX(B.x), iY(B.y));
    A = B;
    if (polygon.isClosed()) // draw side from last to first vertex
    B = (polygon.getVertex(0));
    g.drawLine(iX(A.x), iY(A.y), iX(B.x), iY(B.y));
    } // end of paint
    } // end of class GCanvas

    How about declaring changing centerx and centery in the constructor?

  • Canvas screen

    i'm using the palm os emulator and can't seem to get the whole screen when i want to paint a canvas.
    i use getWidth and getHeight to get the size of the canvas and paints the entire thing but for some reason, there is always an area below that can't be painted. it's the area where all the commands would normally appear. how do i paint the entire screen?

    Hi,
    You cannot use full screen when you are using canvas. for that you have to use FullCanvas whicg comes in MIDP 2.0, but beware not all device supports this, even some device that are MIDP 2.0 compatible does not support FullCanvas.

  • Adding mouselistener on Panel and Canvas

    Hi,
    I m building an application in which I m making a frame, adding a panel on it and then adding a Canvas on the panel. On this Canvas my Native C code is drawing an Image. This image is very small with respect to the size of the frame.
    The size of the Panel and the Canvas is made equal to the size of Image drawn.
    Now I want a mouseclick event on this image.
    Now the problem is that when I add mouselistener to the Panel I don't get any event.
    And when I add mouselistener to the Canvas I get the event but I get the event on the whole frame even if I set the canvas size equal to the drawn image size. I only want the mouse event only if mouse is clicked on the image.
    Can anyone tell the mistake or suggest any other way of doing this ?

    Hi,
    I m building an application in which I m making a frame, adding a panel on it and then adding a Canvas on the panel. On this Canvas my Native C code is drawing an Image. This image is very small with respect to the size of the frame.
    The size of the Panel and the Canvas is made equal to the size of Image drawn.
    Now I want a mouseclick event on this image.
    Now the problem is that when I add mouselistener to the Panel I don't get any event.
    And when I add mouselistener to the Canvas I get the event but I get the event on the whole frame even if I set the canvas size equal to the drawn image size. I only want the mouse event only if mouse is clicked on the image.
    Can anyone tell the mistake or suggest any other way of doing this ?

  • Canvas and BufferedImage display different.

    I use the same method to paint the Canvas and the BufferedImage. But the Graphics2D drawString method
    shows up correctly on the Canvas but not on the BufferedImage (JPEG). Why is there a difference?
    I use the Graphics2D to rotate the text 90 degrees.
    I can't think of any reason why the display comes out different.
    Any suggestions???
    Thanks.

    Here is the code for putting the Canvas graphics onto the BufferedImage (JPEG).
    public void save(HCanvas comp) {
         int w = comp.getWidth();
         int h = comp.getHeight();
         Frame frame = new Frame();
         BufferedImage im = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
         Graphics2D g2 = im.createGraphics();
         g2.setPaint(Color.white);
         g2.fillRect(0,0,w,h);
         g2.setPaint(Color.black);          // back to default color
         comp.paint(g2);                              // Graphics argument
         g2.dispose();
         FileDialog fd = new FileDialog(frame,"Save As JPEG",FileDialog.SAVE);
         fd.show();
         try {
              String dum;
              dum = fd.getDirectory() + fd.getFile();
              OutputStream out = new FileOutputStream(dum);
              JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
              encoder.encode(im);
              out.flush();
              out.close();
              im.flush();
         } catch (Exception FileNotFoundException) {
              String errormsg = "File Not Assigned";
              JOptionPane.showMessageDialog(frame, errormsg);

  • Canvas and BufferedImage display drawString differently.

    I use the same method to paint the Canvas and the BufferedImage. But the Graphics2D drawString method
    shows up correctly on the Canvas but not on the BufferedImage (JPEG). Why is there a difference?
    I use the Graphics2D to rotate the text 90 degrees.
    I can't think of any reason why the display comes out different.
    Any suggestions???
    Thanks.

    Here is the code for putting the Canvas graphics onto the BufferedImage (JPEG).
    public void save(HCanvas comp) {
    int w = comp.getWidth();
    int h = comp.getHeight();
    Frame frame = new Frame();
    BufferedImage im = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = im.createGraphics();
    g2.setPaint(Color.white);
    g2.fillRect(0,0,w,h);
    g2.setPaint(Color.black); // back to default color
    comp.paint(g2); // Graphics argument
    g2.dispose();
    FileDialog fd = new FileDialog(frame,"Save As JPEG",FileDialog.SAVE);
    fd.show();
    try {
    String dum;
    dum = fd.getDirectory() + fd.getFile();
    OutputStream out = new FileOutputStream(dum);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(im);
    out.flush();
    out.close();
    im.flush();
    } catch (Exception FileNotFoundException) {
    String errormsg = "File Not Assigned";
    JOptionPane.showMessageDialog(frame, errormsg);

  • I need help with digital painting

    I have a sketch that I want to add color to but it always turns out flat-looking (if that makes sense). I can't seem to find any good tutorials online on digital painting. Can anyone give me good tips? This is the sketch.

    Chrishonda, I may be missing something but . . Can I say painting in digital is very much like painting in canvas. Have you approached it as putting down some light base color in front of the face, say right cheek there. Brush darker as you move away from the cheek bone toward the temple. less dark as you move toward the nose. Then go back the the cheek bone and put down some lighter tone, right where the light would be reflecting off the cheek bone high spot. In PShop, set your brush options to "Fade" in x pixels, try 25 or maybe 100, depending on size and resolution.
    You might check out a post or 'how to' on 'painting on layers with 50 gray fill'.
    and have fun .

Maybe you are looking for

  • Unable to display a variable value in xml through xsl using coldfusion

    Hi ColdFusion Heroes , Is their any one to help me in this issue . I am new to cold fusion , XML and XSL . Detail Explaination : develoment_files.cfm is a .cfm page , which includes an xml page . development_files_dropdown.xsl is a xsl page . develom

  • How can I wipe my hard drive and clean install Mountain Lion?

    Hi I have a 21.5 inch mid 2011 iMac running Mountain Lion, I want to wipe my hard drive and clean install Mountain Lion. I dont want all my stuff back, just photos and music, the rest I'll reinstall my self. I also dont have a exteranl harddrive. onl

  • Create PDF using DoCmd.Outputto method in legal size page

    I am working in MS Access 2010. I am trying to convert a report to a PDF file.  I am using the following command "DoCmd.Outputto acOutputReport, Report Name, acFormatPDF, FileName".  The report I am using is formatted in legal page size.  When the PD

  • Dual Monitors in Boot Camp

    I have Vista installed under Boot Camp and I am trying to use an external monitor hooked up to my MacBook Pro. However, I have encountered some problems trying to do this. When hooked up the external monitor, the external monitor screen flickers and

  • JDBC Sender Error

    Hi, We have a JDBC Sender adapter configured to pull data from the SQL database. This pulls data for every one hour. Some times we are getting the below error on the communication channel - Database-level error reported by JDBC driver while executing