working on it ...

Filters

Explore Public Snippets

Sort by

Found 5,640 snippets matching: draw

    public by christopher modified May 8, 2014  206223  18  3  0

    Draw things with the turtle api built into python. It can be slow due to fact its not an actual GUI system. However it is fun to toy with.

    Draw things with the turtle api built into python. It can be slow due to fact its not an actual GUI system. However it is fun to toy with.: drawUtils.py
    #import sys #Currently not needed
    import time
    from turtle import *
    
    #Draw a box
    def drawBox(x1, x2, y1, y2, penColor="Black", fillColor="Black"):
        turtle = Turtle()
        d = delay()
        delay(0)
        turtle.hideturtle()
        turtle.up()
        turtle.pencolor(penColor)
        turtle.fillcolor(fillColor)
        turtle.goto(x1, y1)
        turtle.down()
        turtle.begin_fill()
        turtle.goto(x1, y2)
        turtle.goto(x2, y2)
        turtle.goto(x2, y1)
        turtle.goto(x1, y1)
        turtle.end_fill()
        turtle.up()
        del turtle
        delay(d)
        del d
        
    def drawCircle(size,
                   x = None, y = None,
                   usePen = True,
                   useFill = True,
                   fillColor = "Black",
                   penColor = ["Black"],
                   penSize = 5,
                   pieces = 1):
        if (pieces < 1):
            pieces = 1
        if not(usePen) and not(useFill):
            raise Exception("No pen or fill makes this useless! Please specify at least one of them as True")
        turtle = Turtle()
    
        #Store previous delay
        d = delay()
    
        #Set to draw instantly.
        delay(0)
    
    
        turtle.up() #Pickup pen
        turtle.ht() #Hide the turtle
        if (x == None): #Set default value
            x = (0-(size/2))
        if (y == None): #Set default value
            y = (0-(size/2))
        
        turtle.goto(x, y) #Goto co ords
        icM = len(penColor) #Check size of array and limit it.
        if (icM < 1):
            raise Exception("penColor must have at least one entry in array!")
    
        b = 0 #Store the first color index
    
    
        incD =  (360/pieces)#Incrementation of degrees./
        if (useFill):
            turtle.begin_fill()
        if (usePen):
            turtle.down()
            turtle.pensize(penSize)
        for i in range(-1, pieces):
            ic = penColor[b]
            turtle.fillcolor(fillColor)
            turtle.pencolor(ic)
            turtle.circle(size, incD)
            b += 1
            if not(b < icM):
                b = 0
        turtle.end_fill()
        #Reset delay
        delay(d)
    
        del turtle
    
    
    
    
    def drawTriangle(h, w, x = None, y = None, useFill = True, usePen = True, penColor = "Black", fillColor = "Black", penSize = 1):
        if (x == None): #Set default values
            x = 0-(w/2)
        if (y == None): #Set default values
            y = 0-(h/2)
        else:
            y += (h/2)
        x1, x2 = x-(w/2), x+(w/2)
        y1, y2 = y-(h/2), y+(h/2)
        d = delay()
        delay(0)
        turtle = Turtle()
        turtle.ht()
        turtle.up()
        turtle.goto(x1, y1)
        if (useFill):
            turtle.begin_fill()
            turtle.fillcolor(fillColor)
        if (usePen):
            turtle.down()
            turtle.pencolor(penColor)
        print("x1=",x1,"x2=",x2,"y1=", y1,"y2=", y2,"y=", y,"x=", x) #Debug code
        turtle.goto(x2, y1)
        turtle.goto(x, y2)
        turtle.goto(x1, y1)
        turtle.up()
        turtle.end_fill()
        del turtle
        delay(d)
    
    def drawHouse(size, x = 0, y = 0):
        pass
    
    
    
    
    
    ########This is a test area for use Simply uncomment code
    setup()
    title("PLACE TITLE HERE")
    
    ##Use the api below here to create simple drawings on a window. Or do more complex stuff.
    ##This is not exactly a proper module so it can not be imported or atleast I do not think. I am still learning python.
    ##Enjoy!
    
    
    
    
    
    

    public by zonaro modified Oct 23, 2015  205200  1  7  0

    Image toBase64 String

    Extension method to convert a System.Drawing.Image to Base64 String
    public static string toBase64(this System.Drawing.Image OriginalImage)
          {
              using (MemoryStream ms = new MemoryStream())
              {
                  OriginalImage.Save(ms, OriginalImage.RawFormat);
                  byte[] imageBytes = ms.ToArray();
                  return Convert.ToBase64String(imageBytes);
              }
          }
    

    public by Geometry modified Aug 17, 2016  109239  0  5  0

    Random: Creates a rows-by-cols matrix random data drawn from a given distribution.

    Creates a rows-by-cols matrix random data drawn from a given distribution.
    /// <summary>
            ///   Creates a rows-by-cols matrix random data drawn from a given distribution.
            /// </summary>
            /// 
            [Obsolete("Please use INumberGenerator<T> instead.")]
    #pragma warning disable 0618
            public static double[,] Random(int rows, int cols, IRandomNumberGenerator generator)
            {
                return Random<double>(rows, cols, new RandomNumberGeneratorAdapter(generator));
            }

    public by Geometry modified Aug 7, 2016  125188  0  5  0

    FromFile: Load bitmap from file.

    Load bitmap from file. File name to load bitmap from. Returns loaded bitmap. The method is provided as an alternative of method to solve the issues of locked file. The standard .NET's method locks the source file until image's object is disposed, so the file can not be deleted or overwritten. This method workarounds the issue and
    /// <summary>
    /// Load bitmap from file.
    /// </summary>
    /// 
    /// <param name="fileName">File name to load bitmap from.</param>
    /// 
    /// <returns>Returns loaded bitmap.</returns>
    /// 
    /// <remarks><para>The method is provided as an alternative of <see cref="System.Drawing.Image.FromFile(string)"/>
    /// method to solve the issues of locked file. The standard .NET's method locks the source file until
    /// image's object is disposed, so the file can not be deleted or overwritten. This method workarounds the issue and
    /// does not lock the source file.</para>
    /// 
    /// <para>Sample usage:</para>
    /// <code>
    /// Bitmap image = Accord.Imaging.Image.FromFile( "test.jpg" );
    /// </code>
    /// </remarks>
    /// 
    public static System.Drawing.Bitmap FromFile(string fileName)
    {
        Bitmap loadedImage = null;
        FileStream stream = null;
    
        try
        {
            // read image to temporary memory stream
            stream = File.OpenRead(fileName);
            MemoryStream memoryStream = new MemoryStream();
    
            byte[] buffer = new byte[10000];
            while (true)
            {
                int read = stream.Read(buffer, 0, 10000);
    
                if (read == 0)
                    break;
    
                memoryStream.Write(buffer, 0, read);
            }
    
            loadedImage = (Bitmap)Bitmap.FromStream(memoryStream);
        }
        finally
        {
            if (stream != null)
            {
                stream.Close();
                stream.Dispose();
            }
        }
    
        return loadedImage;
    }

    public by micurs modified Oct 30, 2015  32708  465  8  3

    HTML5 Canvas: drawing an arrow at the end of the line

    The Canvas 2D API does not have a way to draw an arrow as endpoint of a line. This simple code shows how you can draw one yourself. With this HTML: Running demo available here: http://jsfiddle.net/n7e2zhj3/2/
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    
    function grid() {
        for (var x = 0.5; x < canvas.width; x += 10) {
            ctx.moveTo(x, 0);
            ctx.lineTo(x, canvas.height);
        }
        for (var y = 0.5; y < canvas.height; y += 10) {
            ctx.moveTo(0, y);
            ctx.lineTo(canvas.width, y);
        }
        ctx.strokeStyle = "#eee";
        ctx.stroke();
    }
    
    function arrow(p1, p2) {
    
        ctx.save();
        var dist = Math.sqrt((p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1]));
    
        ctx.beginPath();
        ctx.lineWidth = 2;
        ctx.strokeStyle = '#0000ff';
        ctx.moveTo(p1[0], p1[1]);
        ctx.lineTo(p2[0], p2[1]);
        ctx.stroke();
    
        var angle = Math.acos((p2[1] - p1[1]) / dist);
    
        if (p2[0] < p1[0]) angle = 2 * Math.PI - angle;
    
        var size = 15;
    
        ctx.beginPath();
        ctx.translate(p2[0], p2[1]);
        ctx.rotate(-angle);
        ctx.fillStyle = '#0000ff';
        ctx.lineWidth = 2;
        ctx.strokeStyle = '#ff0000';
        ctx.moveTo(0, -size);
        ctx.lineTo(-size, -size);
        ctx.lineTo(0, 0);
        ctx.lineTo(size, -size);
        ctx.lineTo(0, -size);
        ctx.closePath();
        ctx.fill();
        ctx.stroke();
        ctx.restore();
    }
    
    $('#myCanvas').bind('mousemove', function (e) {
        var offset = $(this).offset();
        var p1 = [200.0, 200.0];
        var p2 = [e.pageX - offset.left, e.pageY - offset.top];
    
        ctx.clearRect(0, 0, 400, 400);
        grid();
        arrow(p1, p2);
    })                                  

    public by Geometry modified Aug 7, 2016  1167  0  5  0

    Polyline: Draw a polyline on the specified image.

    Draw a polyline on the specified image. Source image data to draw on. Points of the polyline to draw. polyline's color. The method draws a polyline by connecting all points from the first one to the last one. Unlike method, this method does not connect the last point with the first one.
    /// <summary>
    /// Draw a polyline on the specified image.
    /// </summary>
    /// 
    /// <param name="imageData">Source image data to draw on.</param>
    /// <param name="points">Points of the polyline to draw.</param>
    /// <param name="color">polyline's color.</param>
    /// 
    /// <remarks><para>The method draws a polyline by connecting all points from the
    /// first one to the last one. Unlike <see cref="Polygon( BitmapData, List{IntPoint}, Color )"/>
    /// method, this method does not connect the last point with the first one.
    /// </para></remarks>
    /// 
    public static void Polyline(BitmapData imageData, List<IntPoint> points, Color color)
    {
        Polyline(new UnmanagedImage(imageData), points, color);
    }

    public by Geometry modified Aug 7, 2016  905  0  5  0

    Line: Draw a line on the specified image.

    Draw a line on the specified image. Source image data to draw on. The first point to connect. The second point to connect. Line's color. The source image has incorrect pixel format.
    /// <summary>
    /// Draw a line on the specified image.
    /// </summary>
    /// 
    /// <param name="imageData">Source image data to draw on.</param>
    /// <param name="point1">The first point to connect.</param>
    /// <param name="point2">The second point to connect.</param>
    /// <param name="color">Line's color.</param>
    /// 
    /// <exception cref="UnsupportedImageFormatException">The source image has incorrect pixel format.</exception>
    /// 
    public static void Line(BitmapData imageData, IntPoint point1, IntPoint point2, Color color)
    {
        Line(new UnmanagedImage(imageData), point1, point2, color);
    }

    public by Geometry modified Aug 7, 2016  900  0  5  0

    Polygon: Draw a polygon on the specified image.

    Draw a polygon on the specified image. Source image data to draw on. Points of the polygon to draw. Polygon's color. The method draws a polygon by connecting all points from the first one to the last one and then connecting the last point with the first one.
    /// <summary>
    /// Draw a polygon on the specified image.
    /// </summary>
    /// 
    /// <param name="imageData">Source image data to draw on.</param>
    /// <param name="points">Points of the polygon to draw.</param>
    /// <param name="color">Polygon's color.</param>
    /// 
    /// <remarks><para>The method draws a polygon by connecting all points from the
    /// first one to the last one and then connecting the last point with the first one.
    /// </para></remarks>
    /// 
    public static void Polygon(BitmapData imageData, List<IntPoint> points, Color color)
    {
        Polygon(new UnmanagedImage(imageData), points, color);
    }

    public by Geometry modified Aug 7, 2016  616  0  5  0

    Rectangle: Draw rectangle on the specified image.

    Draw rectangle on the specified image. Source image data to draw on. Rectangle's coordinates to draw. Rectangle's color. The source image has incorrect pixel format.
    /// <summary>
    /// Draw rectangle on the specified image.
    /// </summary>
    /// 
    /// <param name="imageData">Source image data to draw on.</param>
    /// <param name="rectangle">Rectangle's coordinates to draw.</param>
    /// <param name="color">Rectangle's color.</param>
    /// 
    /// <exception cref="UnsupportedImageFormatException">The source image has incorrect pixel format.</exception>
    /// 
    public static void Rectangle(BitmapData imageData, Rectangle rectangle, Color color)
    {
        Rectangle(new UnmanagedImage(imageData), rectangle, color);
    }

    public by phuonght modified Jul 15, 2014  1477  0  3  0

    Draw number to marker (Google Map for Android)

    Draw number to marker (Google Map for Android): MainActivity.java
    package asia.idoo.trygmap2;
    
    import android.app.Activity;
    import android.content.Context;
    import android.content.res.Resources;
    import android.graphics.*;
    import android.location.Location;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Toast;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.MapFragment;
    import com.google.android.gms.maps.model.BitmapDescriptorFactory;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.Marker;
    import com.google.android.gms.maps.model.MarkerOptions;
    
    import static android.graphics.Bitmap.Config.ARGB_8888;
    
    public class MainActivity extends Activity {
        private GoogleMap map;
        private int current = 0;
        private Marker marker;
        /**
         * Called when the activity is first created.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            map.setMyLocationEnabled(true);
        }
    
        public void btnMyLocationClick(View v) {
            Location location = map.getMyLocation();
            Toast.makeText(this, location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_SHORT).show();
        }
    
        public void btnNewMarkerClick(View v) {
            Location location = map.getMyLocation();
    
            if (marker != null) {
                marker.remove();
            }
            current++;
            String text = String.valueOf(current);
            Bitmap bitmap = makeBitmap(this, text);
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(new LatLng(location.getLatitude(), location.getLongitude()))
                    .draggable(true)
                    .icon(BitmapDescriptorFactory.fromBitmap(bitmap));
    
            marker = map.addMarker(markerOptions);
        }
    
        public Bitmap makeBitmap(Context context, String text)
        {
            Resources resources = context.getResources();
            float scale = resources.getDisplayMetrics().density;
            Bitmap bitmap = BitmapFactory.decodeResource(resources, R.drawable.marker);
            bitmap = bitmap.copy(ARGB_8888, true);
    
            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(Color.RED); // Text color
            paint.setTextSize(14 * scale); // Text size
            paint.setShadowLayer(1f, 0f, 1f, Color.WHITE); // Text shadow
            Rect bounds = new Rect();
            paint.getTextBounds(text, 0, text.length(), bounds);
    
            int x = bitmap.getWidth() - bounds.width() - 10; // 10 for padding from right
            int y = bounds.height();
            canvas.drawText(text, x, y, paint);
    
            return  bitmap;
        }
    }
    
    
    
    • Public Snippets
    • Channels Snippets