要使用一个图片资源首先需要将其添加到你项目的 res/drawable 文件中。 一旦添加到你的项目中,你就能在 .java 和 .xml 文件中使用它了。 使用的方式就是通过携带文件类型的文件名字 ID 。 例如,my_image.png 在 ID 中的名字为 my_image 。
☆NOTE: 位于 res/drawable 文件夹中的图片资源在编译阶段可能会被 aapt 工具进行无损压缩。 例如,a true-color PNG that doesn't require more than 256 colors may be converted to an 8-bit PNG with a color palette。这种处理方式能在获取同等质量图片的前提下减少图片的内存占用量。 正因为这种操作和处理,项目中的图片文件在编译阶段会被替换。 如果你打算通过二进制六的方式从问佳佳中读取图片,你需要将这些待读取的资源放到 res/raw/ 文件夹下,aapt 不会触及这里的文件。
LinearLayoutmLinearLayout;protectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState); // Create a LinearLayout in which to add the ImageView mLinearLayout =newLinearLayout(this); // Instantiate an ImageView and define its propertiesImageViewi=newImageView(this);i.setImageResource(R.drawable.my_image); // set the ImageView bounds to match the Drawable's dimensionsi.setAdjustViewBounds(true);i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); // Add the ImageView to the layout and set the layout as the content viewmLinearLayout.addView(i);setContentView(mLinearLayout);}
Resources res = mContext.getResources();
TransitionDrawable transition =
(TransitionDrawable) ResourcesCompat.getDrawable(res, R.drawable.expand_collapse, null);
ImageView image = (ImageView) findViewById(R.id.toggle_image);
image.setImageDrawable(transition);
// Then you can call the TransitionDrawable object's methods
transition.startTransition(1000);
public class CustomDrawableView extends View {
private ShapeDrawable mDrawable;
public CustomDrawableView(Context context) {
super(context);
int x = 10;
int y = 10;
int width = 300;
int height = 50;
mDrawable = new ShapeDrawable(new OvalShape());
// If the color isn't set, the shape uses black as the default.
mDrawable.getPaint().setColor(0xff74AC23);
// If the bounds aren't set, the shape can't be drawn.
mDrawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas) {
mDrawable.draw(canvas);
}
}
public class MyDrawable extends Drawable {
private final Paint mRedPaint;
public MyDrawable() {
// Set up color and text size
mRedPaint = new Paint();
mRedPaint.setARGB(255, 255, 0, 0);
}
@Override
public void draw(Canvas canvas) {
// Get the drawable's bounds
int width = getBounds().width();
int height = getBounds().height();
float radius = Math.min(width, height) / 2;
// Draw a red circle in the center
canvas.drawCircle(width/2, height/2, radius, mRedPaint);
}
@Override
public void setAlpha(int alpha) {
// This method is required
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
// This method is required
}
@Override
public int getOpacity() {
// Must be PixelFormat.UNKNOWN, TRANSLUCENT, TRANSPARENT, or OPAQUE
return PixelFormat.OPAQUE;
}
}
MyDrawable mydrawing = new MyDrawable();
ImageView image = findViewById(R.id.imageView);
image.setImageDrawable(mydrawing);