Draw a curved path on canvas?

How to draw a quadratic curve or a trigonometric curve (e.g. sin(x)) on Canvas?

+5
source share
5 answers

Most drawing APIs do not provide such functions, you will have to calculate the pixels of the desired curve in pixels and draw in parts on the canvas using one or more calls to the canvas API.

+1
source

, point(x1, y1) point (x2, y2). , Path (android.graphics.Path). . , , draw . , , . , , .

http://developer.android.com/reference/android/graphics/Path.html

β†’ mPath.moveTo(x1, y1);

β†’ mPath.quadTo(cx, cy, x2, y2);

β†’ canvas.drawPath(mPath, mPaint);

+5

drawEquation(), Graph - , . , ( ),

function(x) = Math.sin(x);

, . TransformContext() canvas, y , :

Graph.prototype.transformContext = function(){
    var canvas = this.canvas;
    var context = this.context;

    // move context to center of canvas
    this.context.translate(this.centerX, this.centerY);

    // stretch grid to fit the canvas window, and 
    // invert the y scale so that that increments
    // as you move upwards
    context.scale(this.scaleX, -this.scaleY);
};

Graph.prototype.drawEquation = function(equation, color, thickness){
    var canvas = this.canvas;
    var context = this.context;

    context.save();
    this.transformContext();

    context.beginPath();
    context.moveTo(this.minX, equation(this.minX));

    for (var x = this.minX + this.iteration; x <= this.maxX; x += this.iteration) {
        context.lineTo(x, equation(x));
    }

    context.restore();
    context.lineJoin = "round";
    context.lineWidth = thickness;
    context.strokeStyle = color;
    context.stroke();

};
+4

, , , . , Math, , . http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html#sin%28double%29 x ( ) y. . x1 (, 1/100 , ), (x2 y2) . . x2, y2 x1, y1 x, , .. "" , , , , .

:

x1 = x;// x - x, .

y1 = sin (x);

x2 = x1 + ,

y2 = sin (x2);

//

x1 = x2; y1 = y2;

// , , , , , , , ( .... 5) "next" increment = increment + 5.

GraphCanvas, , , , , , . : http://www.java2s.com/Code/Java/Swing-Components/GraphCanvas.htm

0

All Articles