1 /*
2  * Copyright 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.test.screenshot.matchers
18 
19 import android.graphics.Bitmap
20 import android.graphics.Color
21 
22 /** Bitmap matching that does an exact comparison of pixels between bitmaps. */
23 class PixelPerfectMatcher : BitmapMatcher {
24 
compareBitmapsnull25     override fun compareBitmaps(
26         expected: IntArray,
27         given: IntArray,
28         width: Int,
29         height: Int
30     ): MatchResult {
31         check(expected.size == given.size)
32 
33         var different = 0
34         var same = 0
35 
36         val diffArray = IntArray(width * height)
37 
38         for (y in 0 until height) {
39             for (x in 0 until width) {
40                 val index = x + y * width
41                 val referenceColor = expected[index]
42                 val testColor = given[index]
43                 if (referenceColor == testColor) {
44                     ++same
45                 } else {
46                     ++different
47                 }
48                 diffArray[index] = diffColor(referenceColor, testColor)
49             }
50         }
51 
52         if (different > 0) {
53             val diff = Bitmap.createBitmap(diffArray, width, height, Bitmap.Config.ARGB_8888)
54             val stats = "[PixelPerfect] Same pixels: $same, " + "Different pixels: $different"
55             return MatchResult(matches = false, diff = diff, comparisonStatistics = stats)
56         }
57 
58         val stats = "[PixelPerfect]"
59         return MatchResult(matches = true, diff = null, comparisonStatistics = stats)
60     }
61 
diffColornull62     private fun diffColor(referenceColor: Int, testColor: Int): Int {
63         return if (referenceColor != testColor) {
64             Color.MAGENTA
65         } else {
66             Color.TRANSPARENT
67         }
68     }
69 }
70