logo
down
shadow

Java draw pixel circle in 2D array


Java draw pixel circle in 2D array

By : sadan49
Date : November 19 2020, 03:01 PM
hope this fix your issue cos and sin functions produce double values from -1 to +1, and when you cast double to int like this: int ElX = (int) (x + x1), some data will be inevitably lost, because such cast just chops the decimal part away. Instead, I suggest rounding double with Math.round, check example below:
code :
System.out.println((int) 0.99);            //  0
System.out.println((int) -0.99);           //  0
System.out.println(Math.round(0.99));      //  1
System.out.println(Math.round(-0.99));     // -1
int ElX = (int) Math.round(x + x1);
int ElY = (int) Math.round(y + y1);
   Before              After

   ******              *****      
  *      *           ***   ***    
 *        *          *       *    
 *        *         **       **   
 *        *         *         *   
 *        **        *         *   
 *        *         *         *   
 *        *         **       **   
  *      *           *       *    
   ******            ***   ***    
      *                *****      


Share : facebook icon twitter icon
How can a draw a circle in java pixel by pixel using a graphical app?

How can a draw a circle in java pixel by pixel using a graphical app?


By : Subeesh ambadikgm
Date : March 29 2020, 07:55 AM
should help you out Here's how I would draw the north-east quarter of a circle, pixel by pixel. You can just repeat this with slight variations for the other three quarters. No trigonometry required!
Start by drawing the eastern most point of the circle. Then you'll draw more pixels, moving northwards and westwards, until you get to the northern most point of the circle. Calculate the distance of the point you've just drawn from the centre. If it's more than the radius, then your next pixel will be one to the left, otherwise, your next pixel will be the one above. Repeat the previous step till you get to the northern most point.
How to draw a circle and line on Google Map pixel-based?

How to draw a circle and line on Google Map pixel-based?


By : Karsten Flindt
Date : March 29 2020, 07:55 AM
I wish did fix the issue. It's easier than you might think, use Symbols.
For a circle there is a predefined path:
code :
new google.maps.Marker({
    position: centerLatLngOfTheCircle,
    icon: {
        path: google.maps.SymbolPath.CIRCLE,
        scale: yourDesiredRadius,
        strokeWeight: 1,
    },
    map: map
});
line = new google.maps.Marker({
    position: startLatLngOfTheLine,
    icon: {
        path: ['M0 0 ', 
               (Math.cos(Math.PI * angle / 180)), 
               (Math.sin(Math.PI * angle / 180))].join(' '),
        scale: desiredStrokeLength,
        strokeWeight: 1
    },
    map: map
});
Android Draw Circle Pixel by Pixel

Android Draw Circle Pixel by Pixel


By : Austin Touch
Date : March 29 2020, 07:55 AM
With these it helps your mistake is a wrong use of ^ , its not a power operator
regarding xfer modes i mentioned in the comment, see this custom view:
code :
class V extends View {
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Xfermode mode = new AvoidXfermode(Color.BLACK, 0, AvoidXfermode.Mode.TARGET);

    public V(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int w = getWidth();
        float h = getHeight() / 3f;
        paint.setXfermode(null);
        paint.setColor(Color.RED);
        canvas.drawRect(0, 0, w, h, paint);
        paint.setColor(Color.BLACK);
        canvas.drawRect(0, h, w, 2*h, paint);
        paint.setColor(Color.GREEN);
        canvas.drawRect(0, 2*h, w, 3*h, paint);

        // draw the circle: it draws only in the middle black strip
        paint.setColor(Color.WHITE);
        paint.setXfermode(mode);
        canvas.drawCircle(w/2, 1.5f * h, h, paint);
    }
}
Draw a circle in canvas manually pixel by pixel

Draw a circle in canvas manually pixel by pixel


By : lkprof
Date : March 29 2020, 07:55 AM
may help you . OK, I've re-factored my earlier code as a jQuery plugin named "canvasLens". It accepts a bunch of options to control things like image src, lens size and border color. You can even choose between two different lens effects, "fisheye" or "scaledSquare".
I've tried to make it as self-explanatory as possible with a header block and plenty of other comments.
code :
/*
 *  Copyright (c) 2014 Roamer-1888
 *  "canvasLens"
 *  a jQuery plugin for a lens effect on one or more HTML5 canvases
 *  by Roamer-1888, 2014-11-09
 *  http://stackoverflow.com/users/3478010/roamer-1888
 * 
 *  Written in response to aa question by Muhammad Umer, here
 *      http://stackoverflow.com/questions/26793321/
 * 
 *  Invoke on a canvas element as follows
 *  $("#canvas").lens({
 *    imgSrc: 'path/to/image',
 *    imgCrossOrigin: '' | 'anonymous' | 'use-credentials', //[1]
 *    drawImageCoords: [ //[2]
 *      0, 0, //(sx,st) Source image sub-rectangle Left,Top.
 *      1350, 788, //(sw/sh) Source image sub-rectangle Width,Height.
 *      0, 0, //(dx/dy) Destination Left,Top.
 *      800, 467 //(dw/dh) Destination image sub-rectangle Width,Height.
 *    ], 
 *    effect: 'fisheye' | 'scaledSquare',
 *    scale: 2 //currently affects only 'scaledSquare'
 *    size: 100, //diameter/side-length of the lens in pixels
 *    hideCursor: true | false,
 *    border: [0, 0, 0, 255] //[r,g,b,alpha] (base-10) | 'none'
 *  });
 * 
 * Demo: http://jsfiddle.net/7z6by3o3/1/
 * 
 * Further reading :
 * [1] imgCrossOrigin - 
 *     https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes
 * [2] drawImageCoords -
 *     https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D
 * 
 * Licence: MIT - http://en.wikipedia.org/wiki/MIT_License
 * 
 * Please keep this header block intact, with amendments 
 * to reflect any changes made to the code.
 * 
 */
(function($){
    // *******************************
    // ***** Start: Private vars *****
    // *******************************
    var pluginName = 'canvasLens';
    // *****************************
    // ***** Fin: Private vars *****
    // *****************************

    // **********************************
    // ***** Start: Private Methods *****
    // **********************************
    // Note that in all private methods,
    // `this` is the canvas on which 
    // the plugin is invoked.
    // Most private methods are called 
    // with `methodName.call(this)`.
    // **********************************
    function animate() {
        var data = $(this).data(pluginName);
        if(data) {
            draw.call(this);
            requestAnimationFrame(animate.bind(this));
        }
    }
    function draw() {
        var data = $(this).data(pluginName);
        data.ctx.drawImage(data.m_can, 0, 0);
        if(data.showLens) {
            if(data.settings.effect == 'scaledSquare') {
                scaledSquare.call(this);
            } else {
                fisheye.call(this);
            }
        }
    }
    function putBg() {
        var data = $(this).data(pluginName);
        data.m_ctx.drawImage.apply(data.m_ctx, [data.img].concat(data.settings.drawImageCoords));
    }
    function scaledSquare() {
        var data = $(this).data(pluginName),
            xt = data.settings.scale,
            h = data.settings.size;
        data.ctx.drawImage(data.m_can,
            data.mouse.x - h/xt/2, data.mouse.y - h/xt/2, //sx,st Source image sub-rectangle Left,Top coordinates.
            h/xt, h/xt, //sw/sh Source image sub-rectangle Width,Height.
            data.mouse.x - h/2, data.mouse.y - h/2, //dx/dy Destination Left,Top coordinates.
            h, h //dw/dh The Width,Height to draw the image in the destination canvas.
        );
    }
    function fisheye() {
        var data = $(this).data(pluginName),
            d = data.settings.size,
            mx = data.mouse.x, my = data.mouse.y,
            srcpixels = data.m_ctx.getImageData(mx - d/2, my - d/2, d, d);
        fisheyeTransform.call(this, srcpixels.data, data.xpixels.data, d, d);
        data.ctx.putImageData(data.xpixels, mx - d/2, my - d/2);
    }
    function fisheyeTransform(srcData, xData, w, h) {
        /*
         *    Fish eye effect (barrel distortion)
         *    *** adapted from ***
         *    tejopa, 2012-04-29
         *    http://popscan.blogspot.co.ke/2012/04/fisheye-lens-equation-simple-fisheye.html
         */
        var data = $(this).data(pluginName),
            y, x, ny, nx, ny2, nx2, r, nr, theta, nxn, nyn, x2, y2, pos, srcpos;
        for (var y=0; y<h; y++) { // for each row
            var ny = ((2 * y) / h) - 1; // normalize y coordinate to -1 ... 1
            ny2 = ny * ny; // pre calculate ny*ny
            for (x=0; x<w; x++) { // for each column
                pos = 4 * (y * w + x);
                nx = ((2 * x) / w) - 1; // normalize x coordinate to -1 ... 1
                nx2 = nx * nx; // pre calculate nx*nx
                r = Math.sqrt(nx2 + ny2); // calculate distance from center (0,0)
                if(r > 1) {
                    /* 1-to-1 pixel mapping outside the circle */
                    /* An improvement would be to make this area transparent. ?How? */
                    xData[pos+0] = srcData[pos+0];//red
                    xData[pos+1] = srcData[pos+1];//green
                    xData[pos+2] = srcData[pos+2];//blue
                    xData[pos+3] = srcData[pos+3];//alpha
                }
                else if(data.settings.border && data.settings.border !== 'none' && r > (1-3/w) && r < 1) { // circular border around fisheye
                    xData[pos+0] = data.settings.border[0];//red
                    xData[pos+1] = data.settings.border[1];//green
                    xData[pos+2] = data.settings.border[2];//blue
                    xData[pos+3] = data.settings.border[3];//alpha
                }
                else if (0<=r && r<=1) { // we are inside the circle, let's do a fisheye transform on this pixel
                    nr = Math.sqrt(1 - Math.pow(r,2));
                    nr = (r + (1 - nr)) / 2; // new distance is between 0 ... 1
                    if (nr<=1) { // discard radius greater than 1.0
                        theta = Math.atan2(ny, nx); // calculate the angle for polar coordinates
                        nxn = nr * Math.cos(theta); // calculate new x position with new distance in same angle
                        nyn = nr * Math.sin(theta); // calculate new y position with new distance in same angle
                        x2 = Math.floor(((nxn + 1) * w) / 2); // map from -1 ... 1 to image coordinates
                        y2 = Math.floor(((nyn + 1) * h) / 2); // map from -1 ... 1 to image coordinates
                        srcpos = Math.floor(4 * (y2 * w + x2));
                        if (pos >= 0 && srcpos >= 0 && (pos+3) < xData.length && (srcpos+3) < srcData.length) { // make sure that position stays within arrays
                            /* get new pixel (x2,y2) and put it to target array at (x,y) */
                            xData[pos+0] = srcData[srcpos+0];//red
                            xData[pos+1] = srcData[srcpos+1];//green
                            xData[pos+2] = srcData[srcpos+2];//blue
                            xData[pos+3] = srcData[srcpos+3];//alpha
                        }
                    }
                }
            }
        }
    }
    // ********************************
    // ***** Fin: Private methods *****
    // ********************************

    // *********************************
    // ***** Start: Public Methods *****
    // *********************************
    var methods = {
        'init': function(options) {
            //"this" is a jquery object on which this plugin has been invoked.
            return this.each(function(index) {
                var can = this,
                    $this = $(this);
                var data = $this.data(pluginName);
                if (!data) { // If the plugin hasn't been initialized yet
                    data = {
                        target: $this,
                        showLens: false,
                        mouse: {x:0, y:0}
                    };
                    $this.data(pluginName, data);

                    var settings = {
                        imgSrc: '',
                        imgCrossOrigin: '',
                        drawImageCoords: [
                            0, 0, //sx,st Source image sub-rectangle Left,Top coordinates.
                            500, 500, //sw/sh Source image sub-rectangle Width,Height.
                            0, 0, //dx/dy Destination Left,Top coordinates.
                            500, 500 //(dw/dh) Destination image sub-rectangle Width,Height.
                        ],
                        effect: 'fisheye',
                        scale: 2,
                        size: 100,
                        border: [0, 0, 0, 255], //[r,g,b,alpha] base-10
                        hideCursor: false
                    };
                    if(options) {
                        $.extend(true, settings, options);
                    }
                    data.settings = settings;

                    if(settings.hideCursor) {
                        data.originalCursor = $this.css('cursor');
                        $this.css('cursor', 'none');
                    }

                    $this.on('mouseenter.'+pluginName, function(e) {
                        data.showLens = true;
                    }).on('mousemove.'+pluginName, function(e) {
                        data.mouse.x = e.offsetX;
                        data.mouse.y = e.offsetY;
                    }).on('mouseleave.'+pluginName, function(e) {
                        data.showLens = false;
                    });
                    data.m_can = $("<canvas>").attr({
                        'width': can.width,
                        'height': can.height
                    })[0];
                    data.ctx = can.getContext("2d"); // lens effect
                    data.m_ctx = data.m_can.getContext('2d'); // background image
                    data.xpixels = data.ctx.getImageData(0, 0, settings.size, settings.size);
                    data.img = new Image();
                    data.img.onload = function() {
                        putBg.call(can);
                        animate.call(can);
                    };
                    data.img.crossOrigin = settings.imgCrossOrigin;
                    data.img.src = settings.imgSrc;
                }
            });
        },
        'destroy': function() {
            return this.each(function(index) {
                var $this = $(this),
                    data = $this.data(pluginName);
                $this.off('mouseenter.'+pluginName)
                    .off('mousemove.'+pluginName)
                    .off('mouseleave.'+pluginName);
                if(data && data.originalCursor) {
                    $this.css('cursor', data.originalCursor);
                }
                $this.data(pluginName, null);
            });
        }
    };
    // *******************************
    // ***** Fin: Public Methods *****
    // *******************************

    // *****************************
    // ***** Start: Supervisor *****
    // *****************************
    $.fn[pluginName] = function( method ) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || !method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' + method + ' does not exist in jQuery.' + pluginName );
        }
    };
    // ***************************
    // ***** Fin: Supervisor *****
    // ***************************
})(jQuery);
how to draw shapes (ellipses, rectange, circle, etc) with line width thicker than 1 pixel

how to draw shapes (ellipses, rectange, circle, etc) with line width thicker than 1 pixel


By : user3347832
Date : March 29 2020, 07:55 AM
I wish this help you I would use draw to draw a 1-pixel thick line, then use skimage.morphology.dilation to "thicken" that line:
code :
import numpy as np
import matplotlib.pyplot as plt
from skimage import draw, morphology

image = np.zeros((128, 128))
rr, cc = draw.ellipse_perimeter(64, 64, 20, 10)
image[rr, cc] = 1
dilated = morphology.dilation(image, morphology.disk(radius=1))
fig, (ax0, ax1) = plt.subplots(1, 2)
ax0.imshow(image)
ax1.imshow(dilated)
Related Posts Related Posts :
  • Interrupt CompletableFuture with default value
  • Eclipse - Choosing servers in "Run on server" vs setting "Target Runtime"
  • Spring JPA doesn't validate bean on update
  • How is takeWhile different from filter?
  • Spring Scheduled Cron jobs firing at wrong time
  • JFrame window resizing on every compile. Different results every time
  • Kotlin unresolved reference :add after converting from Java code
  • How to use Neo4j APOC method " apoc.export.csv.query(query,file,config)" in Java program
  • Regex to include all spanish characters and number
  • Parsing and Mapping a JSON Object with Dynamic Properties
  • Which approach to building domain objects in Spring MVC is more correct?
  • Java Long Min and Max not exact as mentioned in docs
  • Selenium opens new tab after SendKeys
  • How to sort a large array of ints?
  • FitNessse Test can not find Fixture
  • Including Signed Libraries in Executable JAR with Maven
  • If and Else statement run on second iteration of while loop
  • Change class of disabled tab on change of dropdown value
  • Junit5 @ParameterizedTest How to pass array as one of parameter
  • Text message not being sent to a list of numbers but is sent when just one number is specified
  • Spring mapped servlet not called in jetty-maven-plugin
  • How to pace the consumption of a sqs queue using spring integration
  • Autowiring Not getting disabled using xml configuration
  • Maze solve and shortest path with Java BFS
  • Spinner updating only on user actions
  • Why are Java rules for protected access such as they are?
  • Modify parameter of method by value in annotation aspectJ
  • How to send sensitive data to a Liferay portlet from outside the Liferay portal
  • Does a server connection stay open if created inside a method?
  • JAR manifest Class-Path, use folder instead of jar
  • How to do a bulk update in Firestore
  • ItemArray.checklist.add() not appending string to ArrayList
  • How to move something on screen without other picture staying there
  • SpringBoot : No matching bean found exception
  • Implementing the Clonable interface, but don't have to override the clone() method
  • how can i get this code to choose a random word once from each array to print a sentence?
  • Static class to get connections from connection pool
  • Unable to start Chrome browser with user profile in Selenium
  • How to pass a object to be created as a parameter for a method in Java?
  • How to retry with hystrix
  • Loading key to KeyStore fails on Android Oreo
  • Spring+Velocity unsuccessful attempts to save object
  • Private constructor in Kotlin
  • Jetty:run fails with NoSuchMethodError with Spring 5
  • Cannot upload my Web Applicartion in Jboss7 EAP7 EAP
  • How to load a certificate from "Credential storage"?
  • Call Genexus procedure stub in Java environment
  • JavaFX clipping produces a 'lottery scratch ticket'-Effect
  • Using DateTimeFormatter on january first cause an invalid year value
  • Get all the output from Watson conversation using java
  • Java unable to open main class and jar file
  • How to override @override method from activity into another class
  • Adding Runtime VM parameters to intellij for Java 9
  • Java IBM MQ Client connected but not getting messages from queue
  • Questions of Tomcat SSL configuration
  • Stale JNLP files for <extension> (since Java 9?)
  • Properly set (system) properties in JUnit 5
  • Spring MVC Model within POST Method is empty
  • VSTS buildagent: Java 9
  • java.lang.NumberFormatException: For input string: "id" for Hibernate
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org