Last active
May 13, 2022 09:08
-
-
Save Grohden/f40c53bf86c5395638f7a44bf90e732d to your computer and use it in GitHub Desktop.
My view extensions
This file contains 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
package why.android.dont.have.those | |
import android.graphics.Bitmap | |
import android.graphics.Canvas | |
import android.graphics.Color | |
import android.view.View | |
import android.view.ViewGroup | |
import androidx.annotation.ColorRes | |
import androidx.core.content.ContextCompat | |
/** | |
* Sets the color background receiving colorRes | |
*/ | |
fun View.setColorBackground(@ColorRes colorRes: Int) { | |
val color = ContextCompat.getColor(this.context, colorRes) | |
this.setBackgroundColor(color) | |
} | |
/** | |
* Sets the specified margins on the view | |
*/ | |
fun View.setMargins( | |
left: Int? = null, | |
top: Int? = null, | |
right: Int? = null, | |
bottom: Int? = null | |
) { | |
val params = layoutParams as ViewGroup.MarginLayoutParams | |
params.setMargins( | |
left ?: params.leftMargin, | |
top ?: params.topMargin, | |
right ?: params.rightMargin, | |
bottom ?: params.bottomMargin | |
) | |
layoutParams = params | |
} | |
/** | |
* Adds a margin to the specified view | |
*/ | |
fun View.setMarginsRelative( | |
start: Int? = null, | |
top: Int? = null, | |
end: Int? = null, | |
bottom: Int? = null | |
) { | |
val params = layoutParams as ViewGroup.MarginLayoutParams | |
// For some reason, setMarginsRelative is not being recognized by AS, | |
// so I'll have to set prop by prop | |
params.marginEnd = end ?: params.marginEnd | |
params.marginStart = start ?: params.marginStart | |
params.bottomMargin = bottom ?: params.bottomMargin | |
params.topMargin = top ?: params.topMargin | |
layoutParams = params | |
} | |
/** | |
* Returns the view drawable (basically a screenshot of the view) | |
*/ | |
fun View.getBitmapFromView(): Bitmap { | |
val returnedBitmap = Bitmap.createBitmap( | |
measuredWidth, | |
measuredHeight, | |
Bitmap.Config.ARGB_8888 | |
) | |
val canvas = Canvas(returnedBitmap) | |
val bgDrawable = this.background | |
if (bgDrawable != null) { | |
bgDrawable.draw(canvas) | |
} else { | |
canvas.drawColor(Color.TRANSPARENT) | |
} | |
draw(canvas) | |
return returnedBitmap | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment