簡體   English   中英

Android - 如何旋轉矩形對象?

[英]Android - How to rotate Rect Object?

我有一個矩形: Rect r = new Rect(); . 我想將r對象旋轉 45 度。 我檢查了解決方案,我發現它可以用矩陣來完成:

Matrix m = new Matrix();
// point is the point about which to rotate.
m.setRotate(degrees, point.x, point.y);
m.mapRect(r);

問題是我將r傳遞給m.mapRect(r); 它抱怨r應該來自RectF類型。 我設法做到了:

RectF r2 = new RectF(r);
Matrix m = new Matrix();
// point is the point about which to rotate.
m.setRotate(degrees, point.x, point.y);
m.mapRect(r2);

但問題是我需要Rect類型的對象而不是RectF 因為我將r對象傳遞給采用Rect對象的外部類。

除了這種方法之外,還有另一種方法可以旋轉矩形r表單類型Rect並且不旋轉整個畫布(畫布包含一些其他元素)?

先感謝您!

最好的問候, 迪米塔爾·格奧爾基耶夫

以這種方式旋轉矩形不會為您提供任何可用於繪圖的東西。 一個 Rect 和一個 RectF 不存儲任何關於旋轉的信息。 當您使用Matrix.mapRect() ,輸出 RectF 只是一個新的非旋轉矩形,其邊緣接觸您想要的旋轉矩形的角點。

您需要旋轉整個畫布來繪制矩形。 然后立即取消旋轉畫布以繼續繪制,因此旋轉包含其他對象的畫布沒有問題。

canvas.save();
canvas.rotate(45);
canvas.drawRect(r,paint);
canvas.restore();

如果您在矩陣上應用旋轉,則另一種方法是不要使用 mapRect。 您應該找出代表每個矩形邊緣的 4 個初始點並使用 mapPoints 代替。

float[] rectangleCorners = {
                            r2.left, r2.top, //left, top
                            r2.right, r2.top, //right, top
                            r2.right, r2.bottom, //right, bottom
                            r2.left, r2.bottom//left, bottom
                    };
Matrix m = new Matrix();
// point is the point about which to rotate.
m.setRotate(degrees, point.x, point.y);
m.mapPoints(r2);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM