Android 11--横竖屏旋转时背景色异常?
最近遇到一个问题相册打开一张图片横竖屏旋转时有的图片旋转时四周背景色是白色有的则是黑色的。Why? 难不成背景色与图片相关 -- 11.0的问题10.0并无对WMS模块了解一些的人应该都知道横竖屏旋转是系统动画旋转方式以及背景色一般都是由系统设定的。本篇就基于这个问题分析下R的横竖屏旋转时四周背景色的相关流程。关键文件:frameworks\base\services\core\java\com\android\server\wm\ScreenRotationAnimation.javaframeworks\base\services\core\java\com\android\server\wm\utils\RotationAnimationUtils.java首先总结下背景色设置的总体流程这样大家有一个大概的了解横竖屏旋转时的背景色是一个Surface--BackColorSurface定义在ScreenRotationAnimation类中该Surface由冻屏时的截屏确定start color然后由更新方向后的最新界面确定end color然后在旋转动画开始时BackColorSurface也同时执行从start color—end color的颜色更改动画。这是R新添加的小功能可能是为了在横竖屏切换时不那么生硬 比如Q的白色界面在横竖屏旋转背景色都是黑色。下面来一步步梳理下:本篇文章不关心其他内容直接从开始冻屏的地方开始分析ScreenRotationAnimation.ScreenRotationAnimationStep 1. ScreenRotationAnimation.ScreenRotationAnimation/** Only used for custom animations and not screen rotation. */ private SurfaceControl mEnterBlackFrameLayer; /** This layer contains the actual screenshot that is to be faded out. */ private SurfaceControl mScreenshotLayer; /** * Only used for screen rotation and not custom animations. Layered behind all other layers * to avoid showing any empty spots */ private SurfaceControl mBackColorSurface; private BlackFrame mEnteringBlackFrame; private SurfaceRotationAnimationController mSurfaceRotationAnimationController; /** Intensity of light/whiteness of the layout before rotation occurs. */ private float mStartLuma; /** Intensity of light/whiteness of the layout after rotation occurs. */ private float mEndLuma; ScreenRotationAnimation(DisplayContent displayContent, Surface.Rotation int originalRotation) { ...... // 省略一些无关的代码 // 这个我记得以前分析过就是动画的辅助类后面会涉及到 mSurfaceRotationAnimationController new SurfaceRotationAnimationController(); // Check whether the current screen contains any secure content. final boolean isSecure displayContent.hasSecureWindowOnScreen(); final SurfaceControl.Transaction t mService.mTransactionFactory.get(); try { // 这个就是横竖屏旋转时的背景SurfacecolorLayer类型 mBackColorSurface displayContent.makeChildSurface(null) .setName(BackColorSurface) .setColorLayer() .setCallsite(ScreenRotationAnimation) .build(); // RotationLayer: 冻屏时显示在最上方的截屏 mScreenshotLayer displayContent.makeOverlay() .setName(RotationLayer) .setBufferSize(mWidth, mHeight) .setSecure(isSecure) .setCallsite(ScreenRotationAnimation) .build(); mEnterBlackFrameLayer displayContent.makeOverlay() .setName(EnterBlackFrameLayer) .setContainerLayer() .setCallsite(ScreenRotationAnimation) .build(); // 针对custom animation的背景色略 // In case display bounds change, screenshot buffer and surface may mismatch so set a // scaling mode. SurfaceControl.Transaction t2 mService.mTransactionFactory.get(); t2.setOverrideScalingMode(mScreenshotLayer, Surface.SCALING_MODE_SCALE_TO_WINDOW); t2.apply(true /* sync */); // Capture a screenshot into the surface we just created. final int displayId displayContent.getDisplayId(); final Surface surface mService.mSurfaceFactory.get(); surface.copyFrom(mScreenshotLayer); // 截图并返回SurfaceControl.ScreenshotGraphicBuffer SurfaceControl.ScreenshotGraphicBuffer gb mService.mDisplayManagerInternal.systemScreenshot(displayId); if (gb ! null) { Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, ScreenRotationAnimation#getMedianBorderLuma); // 旋转发生之前布局的亮度/白色强度一开始直接根据截屏的边界来设置start color mStartLuma RotationAnimationUtils.getMedianBorderLuma(gb.getGraphicBuffer(), gb.getColorSpace()); Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER); try { surface.attachAndQueueBufferWithColorSpace(gb.getGraphicBuffer(), gb.getColorSpace()); } catch (RuntimeException e) { Slog.w(TAG, Failed to attach screenshot - e.getMessage()); } // If the screenshot containmEnterBlackFrameLayer s secure layers, we have to make sure the // screenshot surface we display it in also has FLAG_SECURE so that // the user can not screenshot secure layers via the screenshot surface. if (gb.containsSecureLayers()) { t.setSecure(mScreenshotLayer, true); } t.setLayer(mScreenshotLayer, SCREEN_FREEZE_LAYER_BASE); // 设置mBackColorSurface的layercolor等并show t.reparent(mBackColorSurface, displayContent.getSurfaceControl()); t.setLayer(mBackColorSurface, -1); t.setColor(mBackColorSurface, new float[]{mStartLuma, mStartLuma, mStartLuma}); t.setAlpha(mBackColorSurface, 1); t.show(mScreenshotLayer); t.show(mBackColorSurface); } else { Slog.w(TAG, Unable to take screenshot of display displayId); } surface.destroy(); } catch (OutOfResourcesException e) { Slog.w(TAG, Unable to allocate freeze surface, e); } ProtoLog.i(WM_SHOW_SURFACE_ALLOC, FREEZE %s: CREATE, mScreenshotLayer); setRotation(t, realOriginalRotation); t.apply(); }Step 2. RotationAnimationUtils.getMedianBorderLuma/** Helper functions for the {link com.android.server.wm.ScreenRotationAnimation} class*/ 这就是个辅助类用于计算背景色以及旋转matrix public class RotationAnimationUtils {} /** * Converts the provided {link GraphicBuffer} and converts it to a bitmap to then sample the * luminance at the borders of the bitmap 转换提供的{link GraphicBuffer}并将其转换为位图然后对位图边界处的亮度进行采样 * return the average luminance of all the pixels at the borders of the bitmap */ 返回位图边界处所有像素的平均亮度 public static float getMedianBorderLuma(GraphicBuffer graphicBuffer, ColorSpace colorSpace) { if (graphicBuffer null || graphicBuffer.getFormat() ! RGBA_8888) { return 0; } ImageReader ir ImageReader.newInstance(graphicBuffer.getWidth(), graphicBuffer.getHeight(), graphicBuffer.getFormat(), 1); ir.getSurface().attachAndQueueBufferWithColorSpace(graphicBuffer, colorSpace); Image image ir.acquireLatestImage(); if (image null || image.getPlanes().length 0) { return 0; } Image.Plane plane image.getPlanes()[0]; ByteBuffer buffer plane.getBuffer(); int width image.getWidth(); int height image.getHeight(); int pixelStride plane.getPixelStride(); int rowStride plane.getRowStride(); float[] borderLumas new float[2 * width 2 * height]; // Grab the top and bottom borders int l 0; for (int x 0; x width; x) { // 抓取上下边界的颜色 borderLumas[l] getPixelLuminance(buffer, x, 0, pixelStride, rowStride); borderLumas[l] getPixelLuminance(buffer, x, height - 1, pixelStride, rowStride); } // Grab the left and right borders for (int y 0; y height; y) { // 抓取左右边界的颜色 borderLumas[l] getPixelLuminance(buffer, 0, y, pixelStride, rowStride); borderLumas[l] getPixelLuminance(buffer, width - 1, y, pixelStride, rowStride); } // Cleanup ir.close(); // Oh, is this too simple and inefficient for you? // How about implementing a O(n) solution? https://en.wikipedia.org/wiki/Median_of_medians Arrays.sort(borderLumas); return borderLumas[borderLumas.length / 2]; // 排序后直接取中间值--相当简单粗暴啊 }private static float getPixelLuminance(ByteBuffer buffer, int x, int y, int pixelStride, int rowStride) { int offset y * rowStride x * pixelStride; int pixel 0; pixel | (buffer.get(offset) 0xff) 16; // R pixel | (buffer.get(offset 1) 0xff) 8; // G pixel | (buffer.get(offset 2) 0xff); // B pixel | (buffer.get(offset 3) 0xff) 24; // A return Color.valueOf(pixel).luminance(); } // 这边的逻辑我没有深入梳理有兴趣的可以继续看下顺便教我一下下。综合上述代码来看就是对截屏的buffer的四边边界颜色进行采样然后取其平均值作为BackColorSurface的颜色.BackColorSurface的初始颜色已经设置完毕现在要进一步看下旋转动画开始时是不是有颜色过渡等操作呢? 那还是要继续来看下代码入口函数就是ScreenRotationAnimation.dismiss—该函数表示满足条件开始执行旋转动画。Step 3. ScreenRotationAnimation.dismiss/** * Returns true if animating. */ public boolean dismiss(SurfaceControl.Transaction t, long maxAnimationDuration, float animationScale, int finalWidth, int finalHeight, int exitAnim, int enterAnim) { if (mScreenshotLayer null) { // Cant do animation. return false; } if (!mStarted) { // 注释已经解释的很详细了就是获取旋转发生之后布局的亮度/白色强度因此参数surface为mDisplayContent.getWindowingLayer() mEndLuma RotationAnimationUtils.getLumaOfSurfaceControl(mDisplayContent.getDisplay(), mDisplayContent.getWindowingLayer()); startAnimation(t, maxAnimationDuration, animationScale, finalWidth, finalHeight, exitAnim, enterAnim); } if (!mStarted) { return false; } mFinishAnimReady true; return true; }Step 4. RotationAnimationUtils.getLumaOfSurfaceControl/** * Gets the average border luma by taking a screenshot of the {param surfaceControl}. * see #getMedianBorderLuma(GraphicBuffer, ColorSpace) */ public static float getLumaOfSurfaceControl(Display display, SurfaceControl surfaceControl) { if (surfaceControl null) { return 0; } Point size new Point(); display.getSize(size); Rect crop new Rect(0, 0, size.x, size.y); SurfaceControl.ScreenshotGraphicBuffer buffer SurfaceControl.captureLayers(surfaceControl, crop, 1); if (buffer null) { return 0; } // 最终还是调用到getMedianBorderLuma只是多了一个captureLayers的操作。 return RotationAnimationUtils.getMedianBorderLuma(buffer.getGraphicBuffer(), buffer.getColorSpace()); }到这一步start color以及end color都已经获取完毕接下来继续看下动画过程。Step 5.ScreenRotationAnimation.startAnimation/** * Returns true if animating. */ private boolean startAnimation(SurfaceControl.Transaction t, long maxAnimationDuration, float animationScale, int finalWidth, int finalHeight, int exitAnim, int enterAnim) { if (mScreenshotLayer null) { // Cant do animation. return false; } if (mStarted) { return true; } mStarted true; ...... // 根据方向change挑选合适的动画并初始化 if (customAnim) { // 我们这里主要讲默认旋转动画而不是customAnim因此这里为false mSurfaceRotationAnimationController.startCustomAnimation(); } else { // DisplayContent构造函数中创建的对象同样定义在ScreenRotationAnimation.java文件中 mSurfaceRotationAnimationController.startScreenRotationAnimation(); } return true; }Step 6. SurfaceRotationAnimationController.startScreenRotationAnimation/** * Utility class that runs a {link ScreenRotationAnimation} on the {link * SurfaceAnimationRunner}. * p * The rotation animation supports both screen rotation and custom animations * * For custom animations: * ul * li * The screenshot layer which has an added animation of its alpha channel * (screen_rotate_alpha) and that will be applied along with the custom animation. * /li * li A device layer that is animated with the provided custom animation /li * /ul * * For screen rotation: * ul * li A rotation layer that is both rotated and faded out during a single animation /li * li A device layer that is both rotated and faded in during a single animation /li * li A background color layer that transitions colors behind the first two layers /li * /ul * * {link ScreenRotationAnimation#startAnimation( * SurfaceControl.Transaction, long, float, int, int, int, int)}. * /ul * * p * Thus an {link LocalAnimationAdapter.AnimationSpec} is created for each of * this three {link SurfaceControl}s which then delegates the animation to the * {link ScreenRotationAnimation}. */ 以上是该类的注释已经解释的很详细了没啥好说的了。 class SurfaceRotationAnimationController {} /** * Start the rotation animation of the display and the screenshot on the * {link SurfaceAnimationRunner}. */ void startScreenRotationAnimation() { try { mService.mSurfaceAnimationRunner.deferStartingAnimations(); // 准备mDisplayContent.getWindowingLayer()的动画即当前更新方向后的最新界面的动画 mDisplayAnimator startDisplayRotation(); // 准备mScreenshotLayer的动画 mScreenshotRotationAnimator startScreenshotRotationAnimation(); // 准备mBackColorSurface的动画本篇只看这个 startColorAnimation(); } finally { mService.mSurfaceAnimationRunner.continueStartingAnimations(); // 开始动画 } }Step 7. SurfaceRotationAnimationController.startColorAnimation/** * Applies the color change from {link #mStartLuma} to {link #mEndLuma} as a * grayscale color */ private void startColorAnimation() { // Total time for the rotation background color transition 旋转背景颜色过渡的总时长200ms int colorTransitionMs mContext.getResources().getInteger( R.integer.config_screen_rotation_color_transition); final SurfaceAnimationRunner runner mService.mSurfaceAnimationRunner; final float[] rgbTmpFloat new float[3]; // 设置start color以及end color final int startColor Color.rgb(mStartLuma, mStartLuma, mStartLuma); final int endColor Color.rgb(mEndLuma, mEndLuma, mEndLuma); // 应用scale这个可以在开发者模式中设置动画缩放为10x可以明显的看到背景颜色有改变 final long duration colorTransitionMs * (long) mService.getCurrentAnimatorScale(); final ArgbEvaluator va ArgbEvaluator.getInstance(); runner.startAnimation( new LocalAnimationAdapter.AnimationSpec() { Override public long getDuration() { return duration; } Override public void apply(SurfaceControl.Transaction t, SurfaceControl leash, long currentPlayTime) { // 动画过程中每一帧设置的颜色都在这里设置就是从startColor过渡到endColor final float fraction getFraction(currentPlayTime); final int color (Integer) va.evaluate(fraction, startColor, endColor); Color middleColor Color.valueOf(color); rgbTmpFloat[0] middleColor.red(); rgbTmpFloat[1] middleColor.green(); rgbTmpFloat[2] middleColor.blue(); if (leash.isValid()) { t.setColor(leash, rgbTmpFloat); } } Override public void dump(PrintWriter pw, String prefix) { pw.println(prefix startLuma mStartLuma endLuma mEndLuma durationMs colorTransitionMs); } Override public void dumpDebugInner(ProtoOutputStream proto) { final long token proto.start(ROTATE); proto.write(START_LUMA, mStartLuma); proto.write(END_LUMA, mEndLuma); proto.write(DURATION_MS, colorTransitionMs); proto.end(token); } }, mBackColorSurface, mDisplayContent.getPendingTransaction(), null); }总体流程已经梳理完毕,那么最开始的疑问也已经得到解释了。横竖屏旋转时的背景色受当前显示的界面影响。系统会根据当前界面的初始方向的界面的边界颜色设置start color以及更新方向后的界面的边界颜色设置end color然后随着旋转动画一起执行color change动画。 那么背景色就与当时显示的图片相关(前提是图片绘制到系统边界处如果显示在正中央不靠近边界那啥影响都不会有。有兴趣的同学可以试下)。如果当时屏幕边界白色占据平均值以上那么则会显示偏白色。因此这个是个系统原生现象不是问题。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2410322.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!