user1517717
user1517717

Reputation: 59

How to crop image inside the path drawn using draw path on canvas,Android

I am able to draw a rectangle using moveTo() and lineTo() commands on Canvas. What I want to do now is to crop the bitmap lying inside this square.

Here is my onDraw() method:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    drawPath.moveTo(topLeft.x, topLeft.y);
    drawPath.lineTo(topRight.x, topRight.y);
    drawPath.lineTo(bottomRight.x, bottomRight.y);
    drawPath.lineTo(bottomLeft.x, bottomLeft.y);
    drawPath.lineTo(topLeft.x, topLeft.y);
    drawCanvas = new Canvas(canvasBitmap);
    canvas.drawPath(drawPath, drawPaint);
    canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
}

Upvotes: 1

Views: 2181

Answers (1)

GareginSargsyan
GareginSargsyan

Reputation: 1895

Try this:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    drawPath.moveTo(topLeft.x, topLeft.y);
    drawPath.lineTo(topRight.x, topRight.y);
    drawPath.lineTo(bottomRight.x, bottomRight.y);
    drawPath.lineTo(bottomLeft.x, bottomLeft.y);
    drawPath.lineTo(topLeft.x, topLeft.y);
    canvas.clipPath(drawPath);
    canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
}

If the drawPath is always a rectangle, you can use Canvas.clipRect(). Here is the same code rewritten using clipRect():

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.clipRect(left, top, right, bottom);
    canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
}

Upvotes: 1

Related Questions