有时候会发现某些组件中各个子view的范围会有交叉,这种情况下没办法通过线性、相对等布局实现。因为view本身所占的区域必须是矩形区域。具体如下:
可以使用FrameLayout进行叠加。
如果图形都一样的话,比如上图。可以使用canvas配合matrix进行旋转,然后绘制。示例如下:
public class LayerView extends View { //apidemo中抄的,不懂 private static final int LAYER_FLAGS = Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG; private Paint mPaint; private Bitmap mBitmap; private int mWidth; private int mHeight; public LayerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public LayerView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public LayerView(Context context) { super(context); init(); } private void init() { mPaint = new Paint(); mPaint.setColor(Color.YELLOW); mPaint.setAntiAlias(true); mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img); mWidth = mBitmap.getWidth(); mHeight = mBitmap.getHeight(); mBitmapMatrix = new Matrix(); } @SuppressWarnings("deprecation") @Override protected void onDraw(Canvas canvas) { Matrix matrix2 = canvas.getMatrix(); saveMatrix(matrix2); for (int x = 0; x < 5; x++) { draw(canvas, matrix2, x * 72); } } private void draw(Canvas canvas, Matrix matrix, int rotate) { canvas.saveLayer(0, 0, getWidth(), getHeight(), null, LAYER_FLAGS); matrix.preTranslate(300 - mWidth, 300 - mHeight); matrix.preRotate(rotate, mWidth / 2, mWidth);//设置旋转中心 canvas.setMatrix(matrix); canvas.drawBitmap(mBitmap, mBitmapMatrix, mPaint); canvas.restore(); restoreMatrix(matrix);//恢复到没有进行改变的状态 } private float[] data = new float[9]; private Matrix mBitmapMatrix; /** * 将matrix的值保存 */ private void saveMatrix(Matrix matrix) { matrix.getValues(data); } /** * 恢复matrix */ private void restoreMatrix(Matrix matrix) { matrix.setValues(data); } }
没有处理点击事件,而且对于比较复杂的直接使用FrameLayout写更方便。