ImageView imageView = (ImageView) findViewById(R.id.imgView);
SVG svg = SVGParser.getSVGFromResource(getResources(), R.drawable.example);
// The following is needed because of image accelaration in some devices, such as Samsung
imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
imageView.setImageDrawable(svg.createPictureDrawable());
你可以像这样精简样板代码:
我很容易地做了一个简单的类来包含过去的代码并减少样板代码,如下所示:
import android.app.Activity;
import android.view.View;
import android.widget.ImageView;
import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;
public class SvgImage {
private static ImageView imageView;
private Activity activity;
private SVG svg;
private int xmlLayoutId;
private int drawableId;
public SvgImage(Activity activity, int layoutId, int drawableId) {
imageView = (ImageView) activity.findViewById(layoutId);
svg = SVGParser.getSVGFromResource(activity.getResources(), drawableId);
// Needed because of image acceleration in some devices, such as Samsung
imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
imageView.setImageDrawable(svg.createPictureDrawable());
}
}
现在我可以在activity中这样调用它:
SvgImage rainSVG = new SvgImage(MainActivity.this, R.id.rainImageView, R.drawable.rain);
SvgImage thunderSVG = new SvgImage(MainActivity.this, R.id.thunderImageView, R.drawable.thunder);
SvgImage oceanSVG = new SvgImage(MainActivity.this, R.id.oceanImageView, R.drawable.ocean);
SvgImage fireSVG = new SvgImage(MainActivity.this, R.id.fireImageView, R.drawable.fire);
SvgImage windSVG = new SvgImage(MainActivity.this, R.id.windImageView,R.drawable.wind);
SvgImage universeSVG = new SvgImage(MainActivity.this, R.id.universeImageView,R.drawable.universe);