简体   繁体   English

在Android画布上绘制一堆旋转矩形

[英]Drawing bunch of rotated rectangles on android canvas

I have a task to draw many rectangles on canvas, but all of them have a rotation angle by which they have to be rotated on canvas. 我的任务是在画布上绘制许多矩形,但是所有矩形都有一个旋转角度,必须在画布上旋转它们。 Many of suggestions I ran into while searching for solution of this problem indicated the way to draw a rectangle and rotate the canvas (Canvas.rotate(angle)), but it rotates all canvas and is only possible with one rectangle. 我在寻找此问题的解决方案时遇到的许多建议都指出了绘制矩形和旋转画布的方式(Canvas.rotate(angle)),但是它旋转了所有画布,并且只能使用一个矩形。 What could be the best way to draw many of rotated rectangles on canvas? 在画布上绘制许多旋转矩形的最佳方法是什么? I want to draw rectangles (single color, with Paint), but not bitmaps, due to time efficiency and memory. 由于时间效率和内存原因,我想绘制矩形(使用Paint绘制单色),而不绘制位图。

The primary way I would do currently is creating a load of canvases and drawing one rectangle on each of them and rotating canvases considering the angle of rectangles. 目前,我要做的主要方法是创建一堆画布,并在每个画布上绘制一个矩形,然后考虑矩形的角度旋转画布。 I think that it is not a smart way due to many canvases and for each of them I should create a separate SurfaceHolder and it is a mess... 我认为由于有许多画布,所以这不是一种明智的方法,对于它们中的每一个,我都应该创建一个单独的SurfaceHolder ,这真是一团糟...

Note that for each rectangle I have coordinates of all of its 4 corners, its width, height, center, angle. 请注意,对于每个矩形,我都有其4个角的全部坐标,即宽度,高度,中心,角度。

You can rotate the canvas for drawing each rectangle, and then restore the original orientation after. 您可以旋转画布以绘制每个矩形,然后再恢复原始方向。 Then set the new rotation for the next rectangle, draw, store, and repeat. 然后为下一个矩形设置新的旋转,绘制,存储并重复。

Approximately this: 大概这个:

  //Save and rotate canvas 
  canvas.save();
  canvas.rotate(angle, pivotX, pivotY);

  canvas.drawRect(...);

  //restore canvas
  canvas.restore();

  // rotate and draw the second rectangle
  canvas.rotate(angle, pivotX, pivotY);

  canvas.drawRect(...);

  canvas.restore();

  // repeat as necessary

where 'angle' is different for each rectangle. 每个矩形的“角度”不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM