从SVG资源加载背景

3

我想使用svg-android将SVG图片作为布局背景加载。

我尝试了这个方法,但是我的布局背景仍然是白色的(在logcat中没有什么特别的信息):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.bg);
    RelativeLayout rl = (RelativeLayout) findViewById(R.id.mainLay);
    rl.setBackground(svg.createPictureDrawable());
}

我做错了什么?
1个回答

3

曾经我也曾困惑过如何在View中放置SVG图像。

下面是一个演示,展示了如何在Android的CustomView中显示SVG图像:

// MainActivity.java
package com.test.svg;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity {

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

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
      WindowManager.LayoutParams.FLAG_FULLSCREEN);

    CustomView view = new CustomView(this);
    view.setBackgroundResource(android.R.color.holo_green_dark);
    setContentView(view);
  }
}

这是关于CustomView类的内容:

// CustomView.java
package com.test.svg;

import java.io.IOException;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.util.AttributeSet;
import android.view.View;

import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParseException;
import com.larvalabs.svgandroid.SVGParser;

public class CustomView extends View {

  private Picture picture;
  private int scaleFactor;

  public CustomView(Context context) {
    super(context);
    initialize();
  }

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

  private void initialize() {
    scaleFactor = 1;
    try {
      setLayerType(View.LAYER_TYPE_SOFTWARE, null); // This is important!!!
      SVG svg = SVGParser.getSVGFromAsset(getContext().getAssets(),
        "Character.svg");
      picture = svg.getPicture();
    } catch (SVGParseException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    // Code for centering the SVG.
    canvas.translate((getWidth() - scaleFactor * picture.getWidth()) >> 1,
      (getHeight() - scaleFactor * picture.getHeight()) >> 1);
    canvas.scale(scaleFactor, scaleFactor);
    canvas.drawPicture(picture);
    canvas.restore();
  }
}

以上片段中重要的是这一行代码:

setLayerType(View.LAYER_TYPE_SOFTWARE, null);

此外,请下载并使用SVG-Android-2代替其第一个版本。
除此之外,您还可以调整此代码以将SVG显示为背景图像。您只需要缩放SVG并让onDraw()方法做其工作即可。
此外,请注意我的SVG图像存储在assets文件夹中,因此我已经按照上面的代码使用了AssetManager来加载SVG。

谢谢您的详细回复,对我帮助很大!但是我使用了SVG.resizePicture方法而不是比例因子,然后将我的Picture转换为PictureDrawable。 - Antoine C.

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