我想創建一個ImageView
剪輯它的內容到一個多邊形內(在這種情況下是一個六邊形)。我的觀點的層類型設置爲軟件,這樣我就可以使用canvas.clipPath()
:ImageView剪切到Polygon
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType (LAYER_TYPE_SOFTWARE, null);
}
產生六角似乎精細的做工代碼:
下面是計算頂點的代碼:
@Override public void calculateVertices() {
width = 2f * radius;
side = 1.5f * radius;
height = (float) Math.sqrt (3f) * radius;
vertices = new Point[6];
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
final float[] p0 = new float[] {center.x - radius, center.y};
final Matrix m = new Matrix();
final float r = getRotation();
for (int i = 0; i < vertices.length; i++) {
final float ptRot = rotateBy (r, (float) i * 60f);
final float[] point = new float[2];
if (ptRot != 0f) {
m.reset();
m.postRotate (ptRot, center.x, center.y);
m.mapPoints (point, p0);
} else {
point[0] = p0[0];
point[1] = p0[1];
}
if (point[0] < minX) {
minX = Math.round (point[0]);
} else if (point[0] > maxX) {
maxX = Math.round (point[0]);
}
if (point[1] < minY) {
minY = Math.round (point[1]);
} else if (point[1] > maxY) {
maxY = Math.round (point[1]);
}
vertices[i] = fromFloat (point);
}
path.reset();
clipPath.reset();
path.moveTo (vertices[0].x, vertices[0].y);
clipPath.moveTo (vertices[0].x, vertices[0].y);
for (int i = 1; i < vertices.length; i++) {
path.lineTo (vertices[i].x, vertices[i].y);
clipPath.lineTo (vertices[i].x, vertices[i].y);
}
path.lineTo (vertices[0].x, vertices[0].y);
clipPath.lineTo (vertices[0].x, vertices[0].y);
path.close();
clipPath.close();
enclosure.set (minX, minY, maxX, maxY);
}
正如您在上面看到的,同樣的方法生成邊界矩形以及定義th的路徑e多邊形和多邊形的剪切路徑。
在該視圖中的構造,path
和clipPath
被定義爲這樣
path = new Path();
clipPath = new Path();
clipPath.setFillType (Path.FillType.INVERSE_EVEN_ODD);
視圖的onDraw
方法被重寫爲這樣:當我使線
@Override protected void onDraw (final Canvas canvas) {
final int count = canvas.save();
canvas.clipPath (hexagon.getClipPath());
super.onDraw (canvas);
hexagon.draw (canvas, selectBackgroundPaint());
canvas.restoreToCount (count);
}
與canvas.clipPath (hexagon.getClipPath());
視圖顯示爲:
4個剪輯點中的2個甚至不在我的路徑上!
我在這裏做錯了什麼?有沒有更好的方法來做到這一點?
最終我希望多邊形以外的所有東西都是透明的。總是。包括選擇突出顯示。
我很感激幫助。我不能發佈太多的代碼(公司IP等),但如果您需要更多的細節,請告訴我,我會更新。這裏
試圖達到什麼樣的?你想要什麼 – MilapTank
一個ImageView,它的內容剪輯到一個多邊形 – copolii
這意味着你的圖像視圖是六角形的權利? – MilapTank