我在流式传输时已为使用画布的全屏图像视图分配了位图。流式传输有效,位图显示在imageview中,但是imageview的活动区域似乎小于其实际大小。当我将背景色设置为imageview时,会得到以下结果:
背景仅填充标记的图像视图的一小部分...
我假设这就是原因,为什么我所有将位图缩放为imageview大小的工作都无法正常进行。
xml:
<androidx.constraintlayout.widget.ConstraintLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.cameraclienttest2.MainActivity">
<ImageView
android:id="@+id/camera_preview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCD5D5"
android:rotation="90"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:onClick="take_photo"
android:text="@string/take_photo"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
将位图分配给imageview:
public void run() {
if (mLastFrame != null) {
mutableBitmap = mLastFrame.copy(Bitmap.Config.RGB_565, true);
if (moffset == OFFSET) {
mBitmap = Bitmap.createBitmap(iv_heigth, iv_width, Bitmap.Config.RGB_565);
mCameraView.setImageBitmap(mBitmap);
mCanvas = new Canvas(mBitmap);
mCanvas.drawBitmap(mutableBitmap, 0, 0, null);
moffset += OFFSET;
}
}
}
Imageview尺寸iv_width,iv_height在创建时签入:
ViewTreeObserver viewTreeObserver = mCameraView.getViewTreeObserver(); //check imageview size
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
mCameraView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
//do some things
iv_width = mCameraView.getWidth();
iv_heigth = mCameraView.getHeight();
}
});
}
我感到非常沮丧,希望有人可以帮助一个孤独的初学者...。
这是由于应用于rotation
的ImageView
。如果删除旋转,您将可以看到ImageView
恢复正常。 Imageview
的高度实际上与父级匹配,宽度也一样。但是,将其旋转90度时,您可以看到宽度为ImageView
的高度,反之亦然。
为了解决此问题,我建议您从应用于xml
的ImageView
布局中删除旋转。您可以改为对可绘制的位图进行处理。将其设置为ImageView
之前,将绘图对象旋转90度,然后将其设置为视图。
Here are a few clever ways将位图旋转90度。为了方便起见,我仅复制此帖子中的一个答案。
public static Bitmap rotateBitmap(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
我希望有帮助!