프로그래밍 방식으로 드로어 블 크기 설정
이미지 (아이콘)의 크기는 거의 같지만 버튼의 높이를 동일하게 유지하려면 크기를 조정해야합니다.
어떻게해야합니까?
Button button = new Button(this);
button.setText(apiEventObject.getTitle());
button.setOnClickListener(listener);
/*
* set clickable id of button to actual event id
*/
int id = Integer.parseInt(apiEventObject.getId());
button.setId(id);
button.setLayoutParams(new LayoutParams(
android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
Drawable drawable = LoadImageFromWebOperations(apiSizeObject.getSmall());
//?resize drawable here? drawable.setBounds(50, 50, 50, 50);
button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
이 setBounds()
방법은 모든 유형의 컨테이너에서 작동하지 않습니다 ( ImageView
그러나 일부 컨테이너에서는 작동했습니다 ).
드로어 블 자체의 크기를 조정하려면 아래 방법을 시도하십시오.
// Read your drawable from somewhere
Drawable dr = getResources().getDrawable(R.drawable.somedrawable);
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
// Scale it to 50 x 50
Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 50, 50, true));
// Set your new, scaled drawable "d"
로 크기 지정 setBounds()
, 즉 50x50 크기 사용
drawable.setBounds(0, 0, 50, 50);
public void setBounds (int left, int top, int right, int bottom)
.setBounds (..)를 적용하기 전에 현재 Drawable을 ScaleDrawable로 변환 해보십시오.
drawable = new ScaleDrawable(drawable, 0, width, height).getDrawable();
그 후
drawable.setBounds(0, 0, width, height);
작동 할 것이다
setBounds () 메서드가 예상대로 비트 맵 드로어 블에서 작동하지 않는 이유를 파헤칠 시간이 없었지만 setBounds가해야 할 일을 수행하기 위해 @ androbean-studio 솔루션을 약간 조정했습니다.
/**
* Created by ceph3us on 23.05.17.
* file belong to pl.ceph3us.base.android.drawables
* this class wraps drawable and forwards draw canvas
* on it wrapped instance by using its defined bounds
*/
public class WrappedDrawable extends Drawable {
private final Drawable _drawable;
protected Drawable getDrawable() {
return _drawable;
}
public WrappedDrawable(Drawable drawable) {
super();
_drawable = drawable;
}
@Override
public void setBounds(int left, int top, int right, int bottom) {
//update bounds to get correctly
super.setBounds(left, top, right, bottom);
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.setBounds(left, top, right, bottom);
}
}
@Override
public void setAlpha(int alpha) {
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.setAlpha(alpha);
}
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.setColorFilter(colorFilter);
}
}
@Override
public int getOpacity() {
Drawable drawable = getDrawable();
return drawable != null
? drawable.getOpacity()
: PixelFormat.UNKNOWN;
}
@Override
public void draw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable != null) {
drawable.draw(canvas);
}
}
@Override
public int getIntrinsicWidth() {
Drawable drawable = getDrawable();
return drawable != null
? drawable.getBounds().width()
: 0;
}
@Override
public int getIntrinsicHeight() {
Drawable drawable = getDrawable();
return drawable != null ?
drawable.getBounds().height()
: 0;
}
}
용법:
// get huge drawable
final Drawable drawable = resources.getDrawable(R.drawable.g_logo);
// create our wrapper
WrappedDrawable wrappedDrawable = new WrappedDrawable(drawable);
// set bounds on wrapper
wrappedDrawable.setBounds(0,0,32,32);
// use wrapped drawable
Button.setCompoundDrawablesWithIntrinsicBounds(wrappedDrawable ,null, null, null);
결과
사용
textView.setCompoundDrawablesWithIntrinsicBounds()
minSdkVersion은 build.gradle에서 17이어야합니다.
defaultConfig {
applicationId "com.example..."
minSdkVersion 17
targetSdkVersion 25
versionCode 1
versionName "1.0"
}
드로어 블 크기를 변경하려면 :
TextView v = (TextView)findViewById(email);
Drawable dr = getResources().getDrawable(R.drawable.signup_mail);
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 80, 80, true));
//setCompoundDrawablesWithIntrinsicBounds (image to left, top, right, bottom)
v.setCompoundDrawablesWithIntrinsicBounds(d,null,null,null);
포스트 방법을 사용하여 원하는 효과를 얻으십시오.
{your view}.post(new Runnable()
{
@Override
public void run()
{
Drawable image = context.getResources().getDrawable({drawable image resource id});
image.setBounds(0, 0, {width amount in pixels}, {height amount in pixels});
{your view}.setCompoundDrawables(image, null, null, null);
}
});
아마 조금 늦었을 것입니다. 그러나 여기에 모든 상황에서 마침내 나를 위해 일한 솔루션이 있습니다.
아이디어는 고정 된 크기의 사용자 정의 드로어 블을 만들고 드로잉 작업을 원본 드로어 블에 전달하는 것입니다.
Drawable icon = new ColorDrawable(){
Drawable iconOrig = resolveInfo.loadIcon(packageManager);
@Override
public void setBounds(int left, int top, int right, int bottom){
super.setBounds(left, top, right, bottom);//This is needed so that getBounds on this class would work correctly.
iconOrig.setBounds(left, top, right, bottom);
}
@Override
public void draw(Canvas canvas){
iconOrig.draw(canvas);
}
@Override
public int getIntrinsicWidth(){
return mPlatform.dp2px(30);
}
@Override
public int getIntrinsicHeight(){
return mPlatform.dp2px(30);
}
};
뷰 유형의 하위 클래스를 만들고 onSizeChanged 메서드를 재정의 할 수 있습니다.
xml 등에서 비트 맵 드로어 블을 정의하는 작업을 엉망으로 만들 필요가없는 내 텍스트 뷰에서 복합 드로어 블을 확장하고 싶었습니다.
public class StatIcon extends TextView {
private Bitmap mIcon;
public void setIcon(int drawableId) {
mIcon = BitmapFactory.decodeResource(RIApplication.appResources,
drawableId);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if ((w > 0) && (mIcon != null))
this.setCompoundDrawablesWithIntrinsicBounds(
null,
new BitmapDrawable(Bitmap.createScaledBitmap(mIcon, w, w,
true)), null, null);
super.onSizeChanged(w, h, oldw, oldh);
}
}
(이 경우에는 아이콘을 텍스트 위에 놓았으므로 아이콘의 높이가 텍스트보기와 같으면 안되므로 h가 아니라 w를 두 번 사용했습니다.)
This can be applied to background drawables, or anything else you want to resize relative to your view size. onSizeChanged() is called the first time the View is made, so you don't need any special cases for initialising the size.
It's been a while since the question was asked
but is still unclear for many how to do this simple thing.
It's pretty simple in that case when you use a Drawable as a compound drawable on a TextView (Button).
So 2 things you have to do:
1.Set bounds:
drawable.setBounds(left, top, right, bottom)
2.Set the drawable appropriately (without using of intrinsic bounds):
button.setCompoundDrawablesRelative(drawable, null, null, null)
- No need to use Bitmaps
- No workarounds such as
ScaleDrawable
ColorDrawable
orLayerDrawable
(what are definitely created for other purposes) - No need in custom drawables!
- No workarounds with the
post
- It's a native and simple solution, just how Android expects you to do.
jkhouw1 답변은 정답이지만 세부 정보가 부족합니다. 아래를 참조하십시오.
API> 21 이상인 경우 훨씬 쉽습니다. 리소스에서 VectorDrawable이 있다고 가정합니다 (검색 할 예제 코드).
val iconResource = context.resources.getIdentifier(name, "drawable", context.packageName)
val drawable = context.resources.getDrawable(iconResource, null)
해당 VectorDrawable에 대해 원하는 크기를 설정하십시오.
drawable.setBounds(0, 0, size, size)
그리고 버튼에 드로어 블 표시 :
button.setCompoundDrawables(null, drawable, null, null)
그게 다야. 그러나 setCompoundDrawables (Intrinsic 버전이 아님)를 사용하십시오!
하나의 레이어와 setLayerInset 메서드에서만 LayerDrawable을 사용할 수 있습니다.
Drawable[] layers = new Drawable[1];
layers[0] = application.getResources().getDrawable(R.drawable.you_drawable);
LayerDrawable layerDrawable = new LayerDrawable(layers);
layerDrawable.setLayerInset(0, 10, 10, 10, 10);
Button button = new Button(this);
Button = (Button) findViewById(R.id.button01);
Button.setHeight()
또는 사용 Button.setWeight()
하고 값을 설정합니다.
참고 URL : https://stackoverflow.com/questions/4609456/set-drawable-size-programmatically
'programing tip' 카테고리의 다른 글
부모 상태 변경 후 React 자식 구성 요소가 업데이트되지 않음 (0) | 2020.10.05 |
---|---|
C ++ 20에서 코 루틴은 무엇입니까? (0) | 2020.10.05 |
테스트 클래스에 대해서만 비공개 메서드를 공개하는 주석 (0) | 2020.10.05 |
어떻게 numpy가 내 Fortran 루틴보다 훨씬 빠를 수 있습니까? (0) | 2020.10.05 |
스칼라 맵의 키와 값 모두 매핑 (0) | 2020.10.05 |