Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
class SmartSize(width: Int, height: Int) {
var size = Size(width, height)
var long = max(size.width, size.height)
var short = min(size.width, size.height)
fun getDisplaySmartSize(context: Context): SmartSize {
val windowManager = context.getSystemService(
Context.WINDOW_SERVICE) as WindowManager
val outPoint = Point()
return SmartSize(outPoint.x, outPoint.y)
fun <T>getPreviewOutputSize(
context: Context, characteristics: CameraCharacteristics, targetClass: Class<T>,
format: Int? = null): Size {
// Find which is smaller: screen or 1080p
val hdSize = SmartSize(1080, 720)
val screenSize = getDisplaySmartSize(context)
val hdScreen = screenSize.long >= hdSize.long || screenSize.short >= hdSize.short
val maxSize = if (hdScreen) screenSize else hdSize
// If image format is provided, use it to determine supported sizes; else use target class
val config = characteristics.get(
val allSizes = if (format == null)
config.getOutputSizes(targetClass) else config.getOutputSizes(format)
// Get available sizes and sort them by area from largest to smallest
val validSizes = allSizes
.sortedWith(compareBy { it.height * it.width })
.map { SmartSize(it.width, it.height) }.reversed()
// Then, get the largest output size that is smaller or equal than our max size
return validSizes.filter {
it.long <= maxSize.long && it.short <= maxSize.short }[0].size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.