詳解 Android中Libgdx使用ShapeRenderer自定義Actor解決無法接收到Touch事件的問題
今天在項目中實現(xiàn)了一個效果,主要是畫一個圓。為了后續(xù)使用方便,將這個圓封裝在一個自定義Actor(CircleActot)中,后續(xù)想顯示一個圓的時候,只要創(chuàng)建一個CircleActor中即可。 部分代碼如下所示:
package com.ef.smallstar.unitmap.widget;import android.content.res.Resources;import com.badlogic.gdx.Gdx;import com.badlogic.gdx.graphics.Color;import com.badlogic.gdx.graphics.g2d.Batch;import com.badlogic.gdx.graphics.g2d.BitmapFont;import com.badlogic.gdx.graphics.glutils.ShapeRenderer;import com.badlogic.gdx.scenes.scene2d.Actor;import com.ef.smallstar.EFApplication;import com.ef.smallstar.R;/** * Created by ext.danny.jiang on 17/4/17. * * A Widget currently used in the UnitMap, shown as a CIRCLE shape * if text not null, there would be a text drawn in the center of the circle */public class CircleActor extends Actor { private float centerX; private float centerY; private String text; private float radius; private ShapeRenderer sr; private BitmapFont bitmapFont; public CircleActor(float x, float y, float radius) { this(x, y, radius, null); } public CircleActor(float x, float y, float radius, String text) { this.centerX = x; this.centerY = y; this.radius = radius; this.text = text; sr = new ShapeRenderer(); } @Override public void act(float delta) { super.act(delta); } @Override public void draw(Batch batch, float parentAlpha) { ... batch.end(); sr.setProjectionMatrix(batch.getProjectionMatrix()); sr.setTransformMatrix(batch.getTransformMatrix()); sr.begin(ShapeRenderer.ShapeType.Filled); sr.circle(centerX, centerY, radius); sr.end(); batch.begin(); ... }然后創(chuàng)建一個Stage對象,并將CircleActor對象添加到Stage中即可顯示。 但是無法給此CircleActor對象添加一個ClickLitener監(jiān)聽。
例如如下代碼:
Stage stage = new Stage();CircleActor ca = new CircleActor(100, 100, 50, "Hello World");ca.addListener(new ClickListener(){ public void click(){ Gdx.app.log("TAG", "ca is clicked"); }})stage.add(ca);上述代碼中的click方法永遠(yuǎn)無法被調(diào)用! 后續(xù)調(diào)了大半天之后終于弄清楚了原因:雖然在CircleActor的draw方法中通過ShapeRenderer.circle方法將一個圓畫到了屏幕上的某一位置,但是此ShapeRenderer其實和Actor之間并沒有太多的聯(lián)系。唯一的聯(lián)系就是以下兩句代碼, 意思應(yīng)該是將ShapeRenderer的camera和Actor對象一致。
sr.setProjectionMatrix(batch.getProjectionMatrix());sr.setTransformMatrix(batch.getTransformMatrix());
但是此時,CircleActor并沒有設(shè)置真正的大小與位置, 因此解決上述問題,需要在構(gòu)造器中將CircleActor的大小和位置與ShapeRenderer做到一致 !!
如下代碼所示,只要添加兩行代碼即可:
public EfCircle(float x, float y, float radius, String text) { this.centerX = x; this.centerY = y; this.radius = radius; this.text = text; //解決ShapeRenderer無法獲取Touch事件 setPosition(centerX - radius, centerY - radius); setSize(radius * 2, radius * 2); sr = new ShapeRenderer(); }如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選