Created
April 14, 2018 08:47
-
-
Save whalemare/b3edab9322788ecf61628640d8f9ee50 to your computer and use it in GitHub Desktop.
Find image in urls by size ImageView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlin.math.abs | |
/** | |
* @since 2018 | |
* @author Anton Vlasov - whalemare | |
*/ | |
object ImageUtils { | |
/** | |
* Choose prefer image size by map entry set. | |
* @param height your avatar holder height in px | |
* @param width your avatar holder width in px | |
* @return null if map == null || resource == null, otherwise prefer image url or original. | |
*/ | |
fun getPreferUrl(height: Int, width: Int, images: List<Background>?): Background? { | |
if (images == null || images.isEmpty()) return null | |
val preferHeight = getClosest(height, images.filter { it.height != null && it.height >= 0 }.map { it.height!! }) | |
val preferWidth = getClosest(width, images.filter { it.width != null && it.width >= 0 }.map { it.width!! }) | |
images.forEach { | |
if (it.width == preferWidth && it.height == preferHeight) { | |
return it | |
} else if (it.height == preferHeight) { | |
return it | |
} else if (it.width == preferWidth) { | |
return it | |
} | |
} | |
return images.firstOrNull() | |
} | |
fun getClosest(middle: Int, numbers: List<Int>): Int { | |
var min = Int.MAX_VALUE | |
var number = middle | |
var delta = 0 | |
numbers.forEach { | |
delta = abs(it - middle) | |
if (delta < min) { | |
min = delta | |
number = it | |
} | |
} | |
return number | |
} | |
} | |
data class Background( | |
val imageUrl: String? = "", | |
val title: String? = "", | |
val width: Int? = null, | |
val height: Int? = null | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment