본문 바로가기

프로그래밍/Android

Assets 폴더의 이미지 읽기

 

커스텀 ImageView

 

Asset폴더는 자주 사용되지는 않지만 이를 활용하여 drawable 리소스와 분리된 이미지 작업이 가능하다.

 

이를 활용하는 예제를 간단히 작성.. 

패키지명은 com.test.app 로 가정한다.

 

1. 커스텀 뷰에서 사용할 attribute 정의

image 라는 String 속성을 사용할 예정인데..

임의로 제약사항을 둔다.

 

여기서는 test_image.png 의 경우 

app:image = "test_image"를 입력하도록 제한.

 

 

res/values/attrs.xml에 속성을 추가한다.

<declare-styleable name="MyImageView">

   <attr name="image" format="string" />

</declare-styleable>

 

 

사용시에는 아래와 같이 사용된다.

<com.test.app xmlns:app = "http://schemas.android.com/apk/com.test.app"

    android:layout_width="128dp"

    android:layout_height="128dp"

    app:image="test_image" />

 

 

2. 커스텀뷰 생성

public class MyImageView extends ImageView {

 

}

 

 

 

3. 레이아웃을 위한 생성자 구성

public class MyImageView extends ImageView {

    final String NameSpace="http://schemas.android.com/apk/res/com.test.app";

    String mImage;

    Context mContext;

 

    public MyImageView( Context context, AttributeSet attrs ) {

mContext = context;

mImage = attrs.getAttributeValue(NameSpace, "image" );

 

// 이미지를 할당한다.

assignImage();

    }

}

 

4. assignImage 함수 작성

위의 제약사항에 test_image만을 입력하도록 했으므로, 확장자를 붙여 읽어준다.

이후 해당 파일이 없으면, 해당 문자열을 id로 바꾸어 R.drawable.test_image를 읽어

오도록한다.

private void assignImage() {

    InputStream is=null;

    Drawable img = null;

 

    try {

        is = mContext.getResource().getAssets().open("폴더/"+mImage+".png");

        img = Drawable.createFromStream( is, null );

        is.close();

    } catch( Exception e) {

        int id = mContext.getResource().getIdentifier("drawable/"+filename,

                                                        null,

                                                        mContext.getPackageName());

        if( id != 0 )

             img = mContext.getResource().getDrawable(id);

    }

 

    setBackgroundDrawable( img );

}

'프로그래밍 > Android' 카테고리의 다른 글

Fragment 기본  (0) 2012.12.28
EditText 특수문자 입력 제한  (0) 2012.09.10
앱 연동  (0) 2012.07.27
Parcelable  (0) 2012.05.22
Data Animation???  (0) 2012.04.18
JSON  (0) 2012.01.31
HTTP POST/GET 몇가지 정리  (0) 2012.01.30
OpenGL es 조명  (0) 2011.12.07
API demos openGL es 2.0  (0) 2011.11.21
GLSurfaceView 배경 투명하게  (1) 2011.11.04