android - Canvas 不显示图像/可绘制

标签 android android-canvas android-view svg-android

我正在做关于 SVG 路径和图像的工作。我已加载 SVG 文件并获取图像并尝试在 Canvas 上设置图像。但是 Canvas 没有显示图像。我检查了此图像/图片的高度和宽度以及空值检查,但它不为空,所以我无法理解为什么 Canvas 不显示图像。任何帮助

我的代码:

public class MainActivity extends Activity{

    Context c;


    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);




        c=getApplicationContext();
        setContentView(new GameView(this));
    }


    public class GameView extends View{
        private int width, height;

        private long svgId;

        Picture picture;

        long startTime;
        float scaleFactor;

        public GameView(Context context) {
            super(context);



            SVG svg = SVGParser.getSVGFromResource(getResources(),R.raw.android);
            picture = svg.getPicture();




        }



        @Override

        protected void onLayout (boolean changed, int left, int top, int right, int bottom) {

            // get visible area

            width = right - left;

            height = bottom - top;

        }



        @Override

        public void onDraw(Canvas canvas) {

            // paint a white background...

            canvas.drawColor(Color.BLACK);

            if (canvas!=null)
            {
                Toast.makeText(c, "yahooooooooooooooooo"+picture.getHeight(), Toast.LENGTH_LONG).show();

                scaleFactor=Math.min((float)getHeight()/picture.getHeight(),(float)getWidth()/picture.getWidth());
                canvas.scale((float)scaleFactor,(float)scaleFactor);
                canvas.drawPicture(picture);
            }

        }

    }
}

最佳答案

svg-android 有一个已知问题,对于某些图像,硬件加速实际上会导致图像不显示。我不确定导致这种情况的确切情况,但我知道它发生在我身上,正如我在 this question 中记录的那样.关键是禁用 View 的硬件加速。根据您的目标,您可能不需要像我那样做一些花哨的事情(Android 3.0+ 不需要检查构建版本),但这是关键部分。将我包含在构造函数中的代码添加到您的构造函数中,然后添加 disableHardwareAcceleration

public GameView(Context context,AttributeSet attrs) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
    {
        disableHardwareAcceleration();
    }
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void disableHardwareAcceleration()
{
    setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

关于android - Canvas 不显示图像/可绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20400697/

相关文章:

java - 更改工具栏溢出图标颜色

Android 基础知识 : running code in the UI thread

android - 调用需要API级别9(当前为8 => WRONG),与android.media.audiofx.Visualizer相关。 (内部图片)

java - 设置应用程序默认android

java - 新 Android API 中的 getMap() 方法对我来说工作不正常

java - 如何重写 Canvas (重用它)

android - 在 View 类 android 中加载布局 xml 文件

android - 无法访问 jarfile ./lib/proguardgui.jar

android - 如何在android Canvas 上绘制圆角多边形?

android - 我的 paintview android 中的重做撤消操作问题