SimplifyingGraphicsWithJavaandThreads(轉(zhuǎn))

Simplifying Graphics With Java and Threads (轉(zhuǎn))[@more@]

Simplifying Graphics With Java and Threads

By Alex Chaffee and John Papageorge
July 1997

普安網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)公司,普安網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為普安成百上千提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的普安做網(wǎng)站的公司定做!

<!-- Begin Main Body Text -->

Here's some code that Earthweb's Alex Chaffee likes to use as an example of how Java can be used to simplify algorithms by combining graphics with threading to render complex graphics.

Basically there are three threads: a Renderer, which performs a complex calculation; an Animator, which wakes up periodically and draws the current image to the screen; and of course the default User Interface thread, which responds to user events and changes the display as appropriate.

The Renderer runs at a low priority—just grinding away forever, or at least until it's done; it shouldn't interfere with the other two threads. The Animator only comes to life every 500 msec or so, to avoid the expense of drawing each pixel.

To perfoRM a specific calculation, subclass the Renderer to make a Mandelbrot function. Note the object-oriented design: this way, the Mandelbrot subclass only needs to override the Run method and doesn't have to worry about the threading implementation, which is handled by its superclass. Of course, in this example, the threading implementation is trivial, but this is a teaching exercise.

Other items of note are the use of an offscreen Graphics buffer, and the use of progressive rendering. The code makes several rough passes over the image, calculating the value in each quadrant, then gradually refines the view. Unlike .NETscape's rendering of progressive gifs, this program treats a calculated pixel as the "center" of a square of color, not as the top corner or a pixel-wide stripe, and so avoids that odd venetian-blind scrolling-up effect. With a laugh, Chaffee says, "But maybe I'm the only one in the world who thought Netscape's gif-rendering algorithm looked funny." now , see Chaffee's source code

/* man.java a test to do threaded animation Copyright (c) 1996 Alex Chaffee, all rights reserved PeRmission is granted to use this source code for instructional purposes as long as copyright information remains intact. @Author: Alex Chaffee */ import java.awt.*; import java.util.*; import java.applet.*; import java.lang.Math; /** * Animator * This class implements the thread that draws the image to the screen * every 500 msec. * @author Alex Chaffee **/ class Animator implements Runnable { static int delay = 500; private Applet applet; private Vector images; private Thread thread = null; private int frame; public Animator(Applet appletIn, Vector imagesIn) { applet = appletIn; images = imagesIn; } public void start() { if (thread == null) { thread = new Thread(this); thread.start(); } } public void stop() { System.out.println("Animator stopped"); thread.stop(); thread = null; } public void run() { thread.setPriority(Thread.MAX_PRIORITY-1); while (thread != null) { applet.repaint(); try { thread.sleep(delay); } catch (InterruptedException e) {}; // Increment frame // Must use synchronized on the off chance that update gets called // between the frame++ and the frame=0 synchronized (this) { frame++; if (frame > images.size()) { frame = 0; } } } } public void paint(Graphics g) { if (frame <images image image="(Image)images.elementAt(frame);" image="if" try it without an imageobserver renderer this class progressively renders the image class renderer implements runnable protected image protected thread thread="null;" thread="protected" int delay="50;" delay="static" int count="0;" count="public" image="imageIn;" image="}" public void if thread="new" thread="Thread(this," public void thread="null;" thread="}" public void public void subclasses renderer in order to implement a mandelbrot function class mandelbrot extends renderer zoom constant protected static float kzoom="(float)1.3;" kzoom="/**" magnification of the image -- mag full span of to>span = 4 / (K^mag)</tt> * @see kZoom */ int mag; /** * point in virtual space around which we're drawing the thing * (i.e. where in virtual space is (0,0) in the window */ float originX = 0; float originY = 0; public Mandelbrot(Image image, int mag, float originX, float originY) { super(image); this.mag = mag; this.originX = originX; this.originY = originY; } static float MagToSpan(int mag) { return 4 / (float)(java.lang.Math.pow(kZoom, mag)); } /** * Render this image progressively. */ public void run() { /** * The graphics port of the image we're drawing to */ Graphics g; g = image.getGraphics(); int width, height; width = image.getWidth(null); height = image.getHeight(null); /** * The width of the window on the virtual space * @see mag */ float span = MagToSpan(mag); /** * current resolution (how big each pixel is) */ int resolution; /** * how far in do we go before we're rendering by pixel */ int resolutionMax = 10; // should calculate based on image size /** * current increment (based on resolution) */ float inc; resolution = 1; int widthPixel, heightPixel; do { // the resolution determines which power of two we're dividing // the span by -- so it fills in by squares float scale = 1 / (float)(java.lang.Math.pow(2, resolution)); inc = span * scale; // pre-calculate the width and height of each "pixel" in the image widthPixel = (int)(scale * width) + 1; heightPixel = (int)(scale * height) + 1; spew("resolution " + resolution + " pixel=(" + widthPixel + ", " + heightPixel + ")"); // Mandelbrot function Color c; int maxiterations = 100; int i; float temp, r, x, y; float minX = originX + inc/2; float maxX = originX + span; float minY = originY + inc/2; float maxY = originY + span; for (float c1= minX; c1 <maxX for nitty merci benoit r="0;" r="x" y="0;" y="i" while r="x*x" r="+" temp="x*x" temp="-" y="2*x*y" y="+" x="temp;" x="i++;" now i is the so base color on it if c="Color.black;" c="}" else all sorts of different color palettes -- we should parameterize c="new" c="Color(i*2," - c="new" c="Color(i*2," - c="new" c="Color(i*2," - c="new" c="Color(i*2," - should optimize by incrementing screen href="tag-273-1.html">os rather than // recalculating int h = (int)(((c1 - originX)*width)/span); int v = (int)(((c2 - originY)*height)/span); // center on the point, not upper-left h -= widthPixel/2; v -= heightPixel/2; g.setColor(c); g.fillRect(h, v, widthPixel, heightPixel); Thread.currentThread().yield(); } /* // even with yield, there's a goofy bug with Netscape 2.0b5 // and lower wherein the browser never takes time for itself // (how selfless). So I'll try sleeping for a millisec just to // see if it helps Thread.currentThread().sleep(1); */ } // for traverse virtual space resolution++; } while (widthPixel > 1 || heightPixel > 1); spew("stopped"); } // method run void spew(String str) { System.out.println("(" + originX + "," + originY + ")x" + mag + ":" + str); } public static int iterate(float c1, float c2) { int maxiterations = 100; // Nitty gritty, merci Benoit float r, x, y, temp; int i; r = 0; x = 0; y = 0; i = 0; while ((i<maxiterations r="x*x" r="+" temp="x*x" temp="-" y="2*x*y" y="+" x="temp;" x="i++;" return man - the main applet class public class man extends applet private int cimages="1;" cimages="private" vector images="null;" images="private" vector renderers="null;" renderers="private" animator animator="null;" animator="float" originx="(float)-2.0;" originx="float" originy="(float)-2.0;" originy="/**" magnification of the first frame in the list int mag="0;" mag="public" void read the parameters string try if originx="new" originx="Float(str).floatValue();" if originy="new" originy="Float(str).floatValue();" if mag="new" mag="Integer(str).intValue();" catch void fill the vector with blank images images="new" images="Vector(cImages);" for i="0;" i="icImages;" image image="createImage(" image="size().width," start each rendering thread renderers="new" renderers="Vector(cImages);" for i="0;" i="icImages;" renderer renderer="new" renderer="Mandelbrot((Image)images.elementAt(i)," start the animator animator="new" animator="Animator(this," a repaint for good measure public void stop all threads public void for i="0;" i="icImages;" must override to reduce flicker public void public void events public boolean int case case zoom in return case zoom out if>0) zoom(mag-1); return true; default: return false; } // switch } // keyDown void zoom(int magNew) { float spanOld = Mandelbrot.MagToSpan(mag); float centerX = originX + spanOld/2; float centerY = originY + spanOld/2; mag = magNew; float spanNew = Mandelbrot.MagToSpan(mag); originX = centerX - spanNew/2; originY = centerY - spanNew/2; stopThreads(); startThreads(); } public boolean mouseDown(Event evt, int x, int y) { System.out.println(evt.toString()); stopThreads(); animator = null; float span = Mandelbrot.MagToSpan(mag); originX = x * span / size().width + originX - span/2; originY = y * span / size().height + originY - span/2; System.out.println("New origin: " + x + (new Dimension(x,y)).toString() + " -> " + originX + "," + originY ); start(); return true; } static float convert(int x, int width, int mag, float origin) { float span = Mandelbrot.MagToSpan(mag); float z = x * span/width + origin; return z; } public boolean mouseMove(Event evt, int x, int y) { float vx = convert(x, size().width, mag, originX); float vy = convert(y, size().height, mag, originY); int i = Mandelbrot.iterate(vx, vy); String str = "i=" + (new Integer(i)).toString(); str = str + " (" + vx + ", " + vy + ")"; getAppletContext().showStatus(str); // System.out.println((new Integer(i)).toString()); return true; } }

網(wǎng)站題目:SimplifyingGraphicsWithJavaandThreads(轉(zhuǎn))
網(wǎng)頁(yè)網(wǎng)址:http://bm7419.com/article38/jdicsp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、網(wǎng)站設(shè)計(jì)公司、微信公眾號(hào)手機(jī)網(wǎng)站建設(shè)、Google營(yíng)銷型網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

小程序開(kāi)發(fā)