package com.codigoparallevar.minicards; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.codigoparallevar.minicards.parts.Part; import com.codigoparallevar.minicards.parts.Placeholder; import com.codigoparallevar.minicards.parts.buttons.RoundButton; import java.util.ArrayList; class PartCanvasView extends View { @NonNull ArrayList parts = new ArrayList<>(); @Nullable Part selectedPart; public PartCanvasView(Context context) { super(context); this.setBackgroundColor(Color.rgb(4, 69, 99)); parts.add(new Placeholder(50, 50, 750, 500)); parts.add(new RoundButton(500, 1200, 80, 100)); } @Override public void onDraw(Canvas canvas){ final long renderStartTime = System.currentTimeMillis(); drawBackground(canvas); for (Part part : parts){ part.draw(canvas); } Log.d("Render time", System.currentTimeMillis() - renderStartTime + "ms"); } private void drawBackground(Canvas canvas) { // Blueprint background final int width = getWidth() + getLeft(); final int height = getHeight() + getTop(); final int cellSize = 50; Paint blueprintLines = new Paint(Paint.ANTI_ALIAS_FLAG); blueprintLines.setColor(Color.argb(100, 255, 255, 255)); // Vertical lines for (int x = cellSize; x < width; x += cellSize){ canvas.drawLine(x, 0, x, height, blueprintLines); } // Horizontal lines for (int y = cellSize; y < height; y += cellSize){ canvas.drawLine(0, y, width, y, blueprintLines); } } @Override public boolean onTouchEvent(MotionEvent event){ final int x = (int) event.getX() - this.getLeft(); final int y = (int) event.getY() - this.getTop(); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: { selectedPart = getPartOn(x, y); if (selectedPart == null) { Log.d("Touched part", "not found"); return false; } Log.d("Touched part", "Part: " + selectedPart); } break; case MotionEvent.ACTION_UP: { selectedPart = null; } break; case MotionEvent.ACTION_MOVE: { if (selectedPart != null){ selectedPart.move(x, y); } } break; default: { Log.d("PartCanvasView", "Unhandled action: " + event.getAction()); } } invalidate(); return true; } @Nullable private Part getPartOn(int x, int y) { // Look in the list, in reverse so top-most elements are checked before for (int i = parts.size() - 1; i >= 0; i--){ final Part part = parts.get(i); if ((x >= part.getLeft()) && (part.getRight() >= x) && (y >= part.getTop()) && (part.getBottom() >= y)){ return part; } } return null; } }