Android绘图网格在背景中

时间:2016-04-13 13:53:24

标签: java android xml

我试图在背景中绘制网格(仅8x8行),但我的绘图视图覆盖了它,并且网格没有显示出来。我的DrawingView处理触摸和绘制圆圈。网格必须在后台绘制网格(当DrawingView消失时它会这样做。)

MainActivity.java:

public class MainActivity extends AppCompatActivity {

private RelativeLayout layout;
private DrawingView drawingView;
private FloatingActionButton pickPhoto;
private final int SELECT_PHOTO = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    layout = (RelativeLayout) findViewById(R.id.layout);
    pickPhoto = (FloatingActionButton) findViewById(R.id.insertPhoto);
    drawingView = (DrawingView) findViewById(R.id.drawingView);
    assert drawingView != null;
    drawingView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
    pickPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, SELECT_PHOTO);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, 0, 0, "Save")
            .setIcon(R.drawable.ic_save)
            .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    FloatingActionMenu fab = (FloatingActionMenu) findViewById(R.id.fab);
                    assert fab != null;
                    fab.setVisibility(View.GONE);
                    Bitmap bitmap = getBitmap(layout);
                    saveChart(bitmap, layout.getMeasuredHeight(), layout.getMeasuredWidth());
                    fab.setVisibility(View.VISIBLE);
                    return false;
                }
            })
            .setShowAsAction(
                    MenuItem.SHOW_AS_ACTION_ALWAYS
                            | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    return super.onCreateOptionsMenu(menu);
}

public void saveChart(Bitmap getbitmap, float height, float width) {
    File folder = new File(Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "My drawings");

    if (!folder.exists()) {
        folder.mkdirs();
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());

    File file = new File(folder.getPath() + File.separator + "/" + timeStamp + ".png");

    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    FileOutputStream ostream;

    try {
        ostream = new FileOutputStream(file);
        Bitmap save = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        Canvas now = new Canvas(save);
        now.drawRect(new Rect(0, 0, (int) width, (int) height), paint);
        now.drawBitmap(getbitmap,
                new Rect(0, 0, getbitmap.getWidth(), getbitmap.getHeight()),
                new Rect(0, 0, (int) width, (int) height), null);
        save.compress(Bitmap.CompressFormat.PNG, 100, ostream);
    } catch (NullPointerException | FileNotFoundException e) {
        e.printStackTrace();
    }
}

public Bitmap getBitmap(RelativeLayout layout) {
    layout.setDrawingCacheEnabled(true);
    layout.buildDrawingCache();
    Bitmap bmp = Bitmap.createBitmap(layout.getDrawingCache());
    layout.setDrawingCacheEnabled(false);
    return bmp;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch (requestCode) {
        case SELECT_PHOTO:
            if (resultCode == RESULT_OK) {
                try {
                    final Uri imageUri = imageReturnedIntent.getData();
                    final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                    drawingView.setImage(selectedImage);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
    }
}

}

DrawingView.java:

class DrawingView extends SurfaceView {

private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private ArrayList<Point> points;
private Bitmap mBitmap;

public DrawingView(Context context, AttributeSet attrs) {
    super(context, attrs);
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.FILL);
    setFocusable(true);
    setFocusableInTouchMode(true);
    points = new ArrayList<>();
    setBackgroundColor(Color.WHITE);
}

@Override
protected void onDraw(Canvas canvas) {
    if (mBitmap != null)
        canvas.drawBitmap(mBitmap, 0, 0, paint);
    for (Point p : points)
        canvas.drawCircle(p.x, p.y, 50, paint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    points.add(new Point((int) event.getX(), (int) event.getY()));
    invalidate();
    return false;
}

public void setImage(Bitmap bitmap) {
    mBitmap = bitmap;
    invalidate();
}

}

Grid.java:

public class Grid extends View{

private int rowsCount = 8;
private int columnsCount = 8;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

public Grid(Context context, AttributeSet attrs) {
    super(context, attrs);
    paint.setColor(Color.BLACK);
}

@Override
protected void onDraw(Canvas canvas) {
    int height = getHeight();
    int width = getWidth();
    for (int i = 0; i < rowsCount; ++i) {
        canvas.drawLine(0, height / rowsCount * (i + 1), width, height / rowsCount * (i + 1), paint);
    }
    for (int i = 0; i < columnsCount; ++i) {
        canvas.drawLine(width / columnsCount * (i + 1), 0, width / columnsCount * (i + 1), height, paint);
    }
    super.onDraw(canvas);
}

}

activity_main.xml中:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layout"
tools:context=".MainActivity"
android:orientation="vertical">

<reminder.com.paint.Grid
    android:id="@+id/grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <reminder.com.paint.DrawingView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/drawingView"
        android:background="#00FFFFFF"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.github.clans.fab.FloatingActionMenu
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        fab:menu_fab_size="normal"
        fab:menu_showShadow="true"
        fab:menu_shadowColor="#66000000"
        fab:menu_shadowRadius="4dp"
        fab:menu_shadowXOffset="1dp"
        fab:menu_shadowYOffset="3dp"
        fab:menu_colorNormal="#DA4336"
        fab:menu_colorPressed="#E75043"
        fab:menu_colorRipple="#99f47070"
        fab:menu_animationDelayPerItem="50"
        fab:menu_icon="@drawable/fab_add"
        fab:menu_buttonSpacing="0dp"
        fab:menu_labels_margin="0dp"
        fab:menu_labels_showAnimation="@anim/fab_slide_in_from_right"
        fab:menu_labels_hideAnimation="@anim/fab_slide_out_to_right"
        fab:menu_labels_paddingTop="4dp"
        fab:menu_labels_paddingRight="8dp"
        fab:menu_labels_paddingBottom="4dp"
        fab:menu_labels_paddingLeft="8dp"
        fab:menu_labels_padding="8dp"
        fab:menu_labels_textColor="#FFFFFF"
        fab:menu_labels_textSize="14sp"
        fab:menu_labels_cornerRadius="3dp"
        fab:menu_labels_colorNormal="#333333"
        fab:menu_labels_colorPressed="#444444"
        fab:menu_labels_colorRipple="#66FFFFFF"
        fab:menu_labels_showShadow="true"
        fab:menu_labels_singleLine="false"
        fab:menu_labels_ellipsize="none"
        fab:menu_labels_maxLines="-1"
        fab:menu_labels_position="left"
        fab:menu_openDirection="up"
        fab:menu_backgroundColor="@android:color/transparent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_gravity="end">

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/insertPhoto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_insert_photo_24dp"
            fab:fab_size="mini"
            fab:fab_label="Add photos" />

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/addCircle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_brightness_1_24dp"
            fab:fab_size="mini"
            fab:fab_label="Add circles" />

    </com.github.clans.fab.FloatingActionMenu>
</RelativeLayout>

0 个答案:

没有答案