首页 > 解决方案 > 使用菜单项在 SurfaceView 上绘制 SVG 图像

问题描述

我想使用 绘制几个 SVG 图像SurfaceView,并且在单击特定菜单项时需要绘制每个图像。菜单中的每个选项都有一个id,当单击一个选项时,我希望id绘制带有该选项的图像。

使用我发现的不同建议,我创建了一个View扩展SurfaceView如下:

public class DrawObject extends SurfaceView {
    private ImageView imageView;
    private Bitmap bmp;
    private SurfaceHolder holder;

    public DrawObject(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DrawObject(Context context, ImageView imageView) {
        super(context);
        this.imageView = imageView;

        holder = getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Canvas canvas = holder.lockCanvas();
                draw(canvas);
                holder.unlockCanvasAndPost(canvas);
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {}
        });

        bmp = BitmapFactory.decodeResource(context.getResources(),imageView.getId());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(imageView!=null) {
            Drawable drawable1 = imageView.getDrawable();
            drawable1.setBounds(100, 100, 0, 0);
            drawable1.draw(canvas);
        }
    }
}

对于我已定义的活动 ( DesignSceneSW),OptionsMenu我创建了以下 XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".DesignSceneSW">

    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/barColor"
        app:title="@string/create_your_design"
        android:id="@+id/toolbar_design"
        app:titleTextColor="@color/textBarColor"
        />
    <com.stud.scriptreality.classes.DrawObject
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/surfaceViewID"
        android:background="@color/textBarColor"
        />
</LinearLayout>

Java文件中我使用DrawObject drawView = findViewById(R.id.surfaceViewID);.

我的问题是我不确定从菜单中单击一个项目时应该如何绘制,因为我不需要将内容设置为setContentView(drawView),因为我需要在同一个表面上绘制多个图像。

我尝试创建另一个DrawObject像:

 public void drawImage(ImageView imv, Canvas canvas) {
    DrawObject dobj = new DrawObject(getApplicationContext(),imv); //the imageView to be drawn
    dobj.draw(canvas);
 }

在我每次点击菜单时都会调用的方法。我读过我不需要创建另一个DrawObject,但只有调用drawView.draw(canvas)对我没有帮助。

我究竟做错了什么?任何建议都非常感谢!

标签: androidimageviewsurfaceviewondrawandroid-optionsmenu

解决方案


推荐阅读