Creating from resource images

         一种简单的增加graphics到你的application的方法是从你的project resources引用an image file。支持的文件类型有PNG (推荐), JPG (可接受) 和 GIF(不建议). 这项技术显然最合适用于application icons, logos, 或者 other graphics 比如用于游戏中的图片文件。

         想要使用image resource,你只需要添加你的文件到你的project的res/drawable/目录下。你可以在你的代码或者XML布局中引用它们。或者你可以使用一个资源ID引用。资源ID是文件名,它没有文件的扩展名。(比如,my_image.png 被引用为 my_image)

        注意:res/drawable/目录下的 Image资源可能会在build过程中被appt工具对其进行无损压缩。例如,一张真彩色的PNG,它不需要超过256色,可能会被转化为 an 8-bit PNG with a color palette. 这将导致同样质量的一张图片但是它确占用更少内存。 所以请意识到在此目录下的 image binaries可能会在build中改变。如果你计划以bit stream的方式读取一张图片,以便再将其转化为一张bitmap,请将此图片放在文件夹 res/raw/ folder下。在此文件夹下它们将不会得到优化。
Example code

下面的代码片段阐述了如何使用drawable资源下的图片生成ImageView,并且将ImageView添加到的布局中去。

LinearLayout mLinearLayout;

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

  // Create a LinearLayout in which to add the ImageView
  mLinearLayout = new LinearLayout(this);

  // Instantiate an ImageView and define its properties
  ImageView i = new ImageView(this);
  i.setImageResource(R.drawable.my_image);
  i.setAdjustViewBounds(true); // set the ImageView bounds to match the Drawable's dimensions
  i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,
  LayoutParams.WRAP_CONTENT));

  // Add the ImageView to the layout and set the layout as the content view
  mLinearLayout.addView(i);
  setContentView(mLinearLayout);
  }

在其他情况下,你可能想要将image资源当作Drawable对象来处理。要达到这样的目的,像如下那样从资源里创建一个Drawable:

 Resources res = mContext.getResources();
 Drawable myImage = res.getDrawable(R.drawable.my_image);
        注意:每个在你工程下的资源只能维持在仅有的一种状态,而不管你为它实例化多少个不同的对象。例如,你实例化了两个Drawable对象,它们都是从相同的image资源而来,然后你改变了其中一个Drawable的属性 (比如alpha) ,这将也会影响另一个Drawable. 所以当你有处理一个image资源的多个实例时,请使用tween动画,而不要直接改造Drawable。

          

Example XML

如下XML片段显示了如何添加一个资源Drawable到ImageView的XML布局中(使用一些色度仅仅为了fun)。

      <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:tint="#55ff0000"
      android:src="@drawable/my_image"/>
  

关于使用工程资源的更多信息,请阅读Resources and Assets。

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值