我不能为我的生活弄清楚如何在Android中显示Bitmap。看起来您只需要调用View.setImageBitmap()
并将其传递给您的位图,但是当我执行此操作时屏幕上不会显示任何内容。如果我打电话给View.invalidate()
,也没有任何事情发生。任何人都能指出我正确的方向吗?这是我生成Bitmap的原因。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ImageView myView = (ImageView) findViewById(R.id.imageView);
Bitmap test = Bitmap.createBitmap(800, 800, Bitmap.Config.ARGB_8888);
test.eraseColor(Color.argb(255, 255, 0, 0));
myView.setImageBitmap(test);
}
这就是内容_ * .xml的样子。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="MyActivity"
tools:showIn="@layout/activity_generator"
android:visibility="visible">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:visibility="visible" />
</RelativeLayout>
答案 0 :(得分:1)
实现这一目标的一种方法是,首先你的类必须扩展View(而不是Activity)。
然后你实施强制性方法:
public myClassName(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(); }
public myClassName(Context context, AttributeSet attrs) {
super(context, attrs);
init(); }
public myClassName(Context context) {
super(context);
init(); }
然后定义你的init():
private void init() {
Bitmap original = BitmapFactory.decodeResource(getResources(),
R.drawable.myVeryOwnChoosedBitmap); //inside your drawable
mBitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mCanvas.drawColor(0xff808080); // bgcolor
mPaint = new Paint();
}
覆盖onDraw():
@Override
protected void onDraw(Canvas canvas) {
drawBMP(canvas);
// In 20ms will be redrawn
postInvalidateDelayed(20);
}
然后drawBMP:
private void drawBMP(Canvas canvas) {
mPaint.setFilterBitmap(false);
canvas.drawBitmap(original, 0, 0, mPaint);
}