动态向视图添加ImageView

4
我正在制作一个使用View类的Android游戏,我没有使用XML布局。
所有的图像都是用画布绘制的。现在我的问题是我不能使用位图。
我试图在我的View类中动态添加一个ImageView,以便使用可触摸事件。
为什么要动态添加?因为我无法使用XML布局。
以下是我的代码:
package com.example.poolmaster;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
    private int cuePosx, cuePosy;

    int cueHeight, cueWeight;
    double rotatingAngle;
    int height;
    int wwidth;
    int cueHeight2, cueWeight2;
    Bitmap table, stick, raise;

    ImageView button = new ImageView(this);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        rotatingAngle = 0;
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        height = displaymetrics.heightPixels;
        wwidth = displaymetrics.widthPixels;
        cueHeight2 = height / 2;
        cueWeight2 = wwidth / 2;
        System.out.println("**************************************");
        System.out.println("height " + height);
        System.out.println("weight" + wwidth);
        System.out.println("**************************************");
      
        // Set generic layout parameters
        GamePlay custom = new GamePlay(this);

        setContentView(custom);
       // setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_MOVE){
            // cuePosy += 10;
            // System.out.println("xCORDİNATES!!!! " +ev.getX());
            // System.out.println("yCORDİNATES!!!! " +ev.getY());
            rotatingAngle=getAngle(ev.getX(), ev.getY());
            System.out.println("Angle " +rotatingAngle);
        }
        if (ev.getAction()==MotionEvent.ACTION_DOWN){
            System.out.println("****************** ACTİON DOWN ****************");
            // cueHeight2 += 10;
            // cueWeight2 += 20;
            // cuePosy = 320;
        }
        if (ev.getAction()==MotionEvent.ACTION_UP){
            System.out.println("****************** ACTİON DOWN ****************");
            // cueHeight2 -= 10;
            // cueWeight2 -= 20;
            // cuePosy = 320;
        }
        return true;
    }
    private double getAngle(double xTouch, double yTouch) {
        double theta;
        
        theta = Math.toDegrees(Math.atan2(height / 2 - yTouch, xTouch - wwidth / 2));
        return theta;
    }
    
    public class GamePlay extends View {
        public GamePlay(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
            table = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
            table = Bitmap.createScaledBitmap(table, wwidth, height, true);
            stick = BitmapFactory.decodeResource(getResources(), R.drawable.stick);

            raise = BitmapFactory.decodeResource(getResources(), R.drawable.raise);
            cueHeight = stick.getHeight();
            System.out.println("ıstaka " + cueHeight);
            cueWeight = stick.getWidth();
            cuePosx = wwidth / 2;
            cuePosy = height - cueHeight - 180;
        }
        @SuppressLint({ "DrawAllocation", "DrawAllocation" })
        @Override
        public void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            Matrix matrix = new Matrix();
            matrix.setTranslate(cueWeight2, cueHeight2);
            matrix.postRotate((float)rotatingAngle, cueWeight2, cueHeight2); // anti-clockwise by 90 degrees
               
            // create a new bitmap from the original using the matrix to transform the result
            Bitmap rotatedBitmap = Bitmap.createBitmap(stick, 0, 0, stick.getWidth(), stick.getHeight(), matrix, false);
               
            canvas.save(); // Save the position of the canvas.
            canvas.restore();
               
            // Rotate the canvas.
            canvas.drawBitmap(table, 0, 0, null); // Draw the ball on the rotated canvas.
            canvas.drawBitmap(stick, matrix, null);
            canvas.drawBitmap(raise, 0, 0, null);
            invalidate();
        }
    }
}

如果我的答案对您有帮助,请接受它,这样也可以帮助其他人。 - Dipak Keshariya
2个回答

4

这是将ImageView添加到扩展了Activity类的布局中的方法

   LinearLayout lL = findViewById(R.id.xmlfile_layout_id);

   ImageView imgView = new ImageView(context); 

   imgView.setVisibility(View.VISIBLE);
   lL.addView(imgView);

如何在继承View类的情况下向画布添加ImageView

通常情况下,无法直接在画布上放置ImageView、EditText或按钮等控件,需要通过绘制来实现。因此,您需要创建一个自定义布局,并使用画布绘制该布局。

可以尝试以下方法,在onDraw(..)中调用:

   LinearLayout lL = new LinearLayout(context);

   ImageView imgView = new ImageView(context); 

   imgView.setVisibility(View.VISIBLE);
   lL.addView(imgView);

    lL.measure(canvas.getWidth(), canvas.getHeight());
    lL.layout(0, 0, canvas.getWidth(), canvas.getHeight());

    // placing the edit text at specific co-ordinates:
    //canvas.translate(0, 0);
    layout.draw(canvas);

看看这个另一个例子:点击这里 它提供了另一种添加视图的方式。

是的,您可以将此图像添加到任何视图中。 - itsrajesh4uguys
现在没有异常了,但屏幕上没有图像。 - Tunç Doğan
现在移除这行代码:lL.draw(canvas); 我不确定,试一下。 - RajeshVijayakumar
当执行lL.addView(imgView);时,出现了异常12-22 14:01:16.682: E/AndroidRuntime(1520): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. - Tunç Doğan
如果您删除 lL.addView(imgView); 这行代码会发生什么? - RajeshVijayakumar
显示剩余3条评论

0

使用以下代码实现。

动态创建 ImageView:

ImageView mImgView1 = new ImageView(this);

如果您要将其添加到视图中,请在setContentView(custom);之前编写以下代码(如果GamePlay是您的视图类)

custom.add(mImgView1);

1
是的,Gameplay是我的View类(public void GamePlay extends View),写法就像这样。然而,没有像custom.add这样的方法。 - Tunç Doğan
@TunçDoğan 那请自行搜索,因为我不知道如何在自定义视图类中添加 add() 方法。 - Dipak Keshariya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接