Image show in android

Android. Вывод изображений, различные способы

Эта статья будет полезна начинающим разработчикам, здесь я предложу несколько вариантов вывода изображений на Android. Будут описаны следующие способы:

Обычный метод – стандартный способ, используя ImageView. Рассмотрены варианты загрузки картинки из ресурса, а также из файла на SD карте устройства.

Продвинутый вариант — вывод изображения, используя WebView. Добавляется поддержка масштабирования и прокрутки картинки при помощи жестов.

“Джедайский” способ – улучшенный предыдущий вариант. Добавлен полноэкранный просмотр с автоматическим масштабированием изображения при показе и поддержкой смены ориентации устройства.

Исходники тестового проекта на GitHub github.com/Voldemar123/andriod-image-habrahabr-example

В этой статье я не рассматриваю вопросы загрузки изображений из Интернета, кеширования, работы с файлами и необходимых для работы приложения permissions – только вывод картинок.

Итак, задача — предположим, в нашем приложении необходимо вывести изображение на экран.
Картинка может размерами превышать разрешение экрана и иметь различное соотношение сторон.
Хранится она либо в ресурсах приложения, либо на External Storage — SD карте.

Также допустим, мы уже записали на карту памяти несколько изображений (в тестовом проекте – загружаем из сети). Храним их в каталоге данных нашего приложения, в кеше.

public static final String APP_PREFS_NAME = Constants.class.getPackage().getName();
public static final String APP_CACHE_PATH =
Environment.getExternalStorageDirectory().getAbsolutePath() +
«/Android/data/» + APP_PREFS_NAME + «/cache/»;

Layout, где выводится картинка

android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:orientation=»vertical» >

Масштабирование по умолчанию, по меньшей стoроне экрана.
В Activity, где загружаем содержимое картинки

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageView1);

Из ресурсов приложения (файл из res/drawable/img3.jpg)

Задавая Bitmap изображения

FileInputStream fis = new FileInputStream(Constants.APP_CACHE_PATH + this.image);
BufferedInputStream bis = new BufferedInputStream(fis);

Bitmap img = BitmapFactory.decodeStream(bis);

Или передать URI на изображение (может хранится на карте или быть загружено из сети)

mImageView.setImageURI( imageUtil.getImageURI() );
Uri.fromFile( new File( Constants.APP_CACHE_PATH + this.image ) );

Этот способ стандартный, описан во множестве примеров и поэтому нам не особо интересен. Переходим к следующему варианту.

Предположим, мы хотим показать большое изображение (например фотографию), которое размерами превышает разрешение нашего устройства. Необходимо добавить прокрутку и масштабирование картинки на экране.

android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:orientation=»vertical» >

В Activity, где загружаем содержимое

protected WebView webView;
webView = (WebView) findViewById(R.id.webView1);

установка черного цвета фона для комфортной работы (по умолчанию – белый)

включаем поддержку масштабирования

больше места для нашей картинки

webView.setPadding(0, 0, 0, 0);

полосы прокрутки – внутри изображения, увеличение места для просмотра

загружаем изображение как ссылку на файл хранящийся на карте памяти

webView.loadUrl(imageUtil.getImageFileLink() );
«file:///» + Constants.APP_CACHE_PATH + this.image;

Теперь мы хотим сделать так, чтобы картинка при показе автоматически масштабировалась по одной из сторон, при этом прокрутка остается только в одном направлении.
Например, для просмотра фотографий более удобна ландшафтная ориентация устройства.
Также при смене ориентации телефона масштаб изображения должен автоматически меняться.
Дополнительно расширим место для просмотра изображения на полный экран.

Читайте также:  Лунный календарь для андроида

В AndroidManifest.xml для нашей Activity добавляем

В код Activity добавлен метод, который вызыватся при каждом повороте нашего устройства.

@Override
public void onConfigurationChanged(Configuration newConfig) <
super.onConfigurationChanged(newConfig);
changeContent();
>

В приватном методе описана логика пересчета масштаба для картинки
Получаем информацию о размерах дисплея. Из-за того, что мы изменили тему Activity, теперь WebView раскрыт на полный экран, никакие другие элементы интерфейса не видны. Видимый размер дисплея равен разрешению экрана нашего Android устройства.

Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

int width = display.getWidth();
int height = display.getHeight();

Размеры изображения, выбранного для показа

Bitmap img = imageUtil.getImageBitmap();

int picWidth = img.getWidth();
int picHeight = img.getHeight();

Меняем масштаб изображения если его высота больше высоты экрана. Прокрутка теперь будет только по горизонтали.

if (picHeight > height)
val = new Double(height) / new Double(picHeight);

Подбрасываем в WebView специально сформированный HTML файл, содержащий изображение.

webView.loadDataWithBaseURL(«/»,
imageUtil.getImageHtml(picWidth, picHeight),
«text/html»,
«UTF-8»,
null);

StringBuffer html = new StringBuffer();

Такой способ я применил из-того, что после загрузки изображения в WebView через метод loadUrl, как в прошлом варианте, setInitialScale после поворота устройства не изменяет масштаб картинки. Другими словами, показали картинку, повернули телефон, масштаб остался старый. Очень похоже на то, что изображение как-то кешируется.

Я не нашел в документации упоминания об этом странном поведении. Может быть местные специалисты скажут, что я делаю не так?

Источник

Implementing the Perfect Splash Screen in Android

Splash Screen is the first screen visible to the user when the application’s launched. It’s a vital screen that will allow the users to have first impressions of the application.

A Splash Screen is a screen that appears when you open an app on your mobile device. Sometimes it’s referred to as a launch screen or startup screen and shows up when your app is loading after you’ve just opened it.

When the loading is finished, you’ll be taken to a more functional screen where you can complete actions.

Splash screens appear on your screen for a fleeting moment — look away and you might miss them. The splash screen is one of the most vital screens in the application since it’s the user’s first experience with the application.

There are 2 common methods of implementing splash screens and will find the right way:

  1. Using Timers (the bad)
  2. Using a Launcher Theme (The Right way)

Using timer (Our 1st Method) into your activity to display splash, we create a splash activity and create a thread in onCreate() for shows up for 2/3 seconds, then go to our desired activity. Here, see the implementation of this easy method:

The above approach isn’t the correct approach. It’ll give rise to cold starts.

The purpose of a Splash Screen is to quickly display a beautiful screen while the application fetches the relevant content if any (from network calls/database). With the above approach, there’s an additional overhead that the SplashActivity uses to create its layout.

It’ll give rise to slow starts to the application which is bad for the user experience (wherein a blank black/white screen appears).

The cold start appears since the application takes time to load the layout file of the Splash Activity. So instead of creating the layout, we’ll use the power of the application theme to create our initial layout (Our 2nd Method).

Читайте также:  Рейтинг звонилок для андроид 2021

Application theme is instantiated before the layout is created. We’ll set a drawable inside the theme that’ll comprise the Activity’s background and an icon using layer-list as shown below.

Do you know when an activity is called Android OS first see in the manifest is there any theme for that activity and load the theme from manifest?

So, we will set a custom theme in Manifest for our splash activity. To create the theme for the splash screen, follow the below process.

Step 1

Create Background for Splash Screen in drawable/splash_background.xml, the bitmap is the image we want to show.

Step 2

Create the gradient onto which your app logo will be placed in drawable/bg_gradient.xml, background can be a gradient or any colour depending on your app.

Step 3

Create Style for Splash Screen in res/values/themes.xml

Step 4

Create an empty Activity named SplashScreenActivity and set the style as the theme for it in AndroidManifest.xml

Step 5

Setting the Intent to your MainActivity.java from SplashScreenActivity.java

As we are loading the splash screen them from manifest, there is no need to setContentView() with any xml layout. If you want to show your splash screen for some amount of time (like five secs) you can create a Handler , also using a timer can help you fetch data from the cloud on your MainActivity which could be a better approach than to show a dialog on home screen.

Using the theme and removing the layout from the SplashScreenActivity is the correct way to create a splash screen 🙌.

Now that our splash is working, what size of the image should I put into a drawable folder?

Always put your app_logo.png into drawable-xxhdpi folder so that your logo automatically scales for all types of phone screens in most cases.

Also, make sure that image resolution is not more than 1000×1000 pixels . It can have less resolution depending on how you want it. Now there are diverse types of splash screen which has multiple logos on various parts of the screen. How that could be done?

From the above example, we implemented our method to create a splash like Twitter, and now to create one like Facebook we just make a slight change to our drawable/splash_background.xml.

Just add as many item to your layer-list you want to place in your splash screen.

Splash screen best practices

Splash screens are simple. They’re used to enhance a brand and give users something nice to look at as they wait. In this regard, here are some best practices for when you design your own splash screen:

  • Keep it free from unnecessary distraction
  • Don’t use multiple colours or logos
  • Use animation sparingly

Hope it helped. Happy Coding 😀

BTW, I solve real-world problems by building useful apps. Have a look at my portfolio .

Источник

Image show in android

A simple and customizable full-screen image viewer with shared image transition support, «pinch to zoom» and «swipe to dismiss» gestures. Compatible with all of the most popular image processing libraries such as Picasso , Glide etc. Based on PhotoView by chrisbanes.

Читайте также:  Kotlin для чайников android

Need iOS and Android apps, MVP development or prototyping? Contact us via info@stfalcon.com. We develop software since 2009, and we’re known experts in this field. Check out our portfolio and see more libraries from stfalcon-studio.

  • A project configured with the AndroidX
  • SDK 19 and and higher

Download via Gradle:

Add this to the project build.gradle file:

And then add the dependency to the module build.gradle file:

Download via Maven:

Where the latest_version is the value from Download badge.

All you need to show the viewer is to pass the context, list or array of your image objects and the implementation of the ImageLoader and call the show() method:

To improve the UX of your app you would like to add a transition when a user opens the viewer. And this is simple as never before! Just tell the viewer which image should be used for animation using withTransitionFrom(myImageView) method and the library will do it for you!

If you need more advanced behavior like updating transition target while changing images in the viewer please see the sample app for how to do this.

Update images list on the fly

There are a lot of common cases (such as pagination, deleting, editing etc.) where you need to update the existing images list while the viewer is running. To do this you can simply update the existing list (or even replace it with a new one) and then call updateImages(images) .

Change current image

Images are not always leafed through by the user. Maybe you want to implement some kind of preview list at the bottom of the viewer — setCurrentPosition is here for help. Change images programmatically wherever you want!

Custom overlay view

If you need to show some content over the image (e.g. sharing or download button, description, numeration etc.) you can set your own custom view using the setOverlayView(customView) and bind it with the viewer through the ImageViewer.OnImageChangeListener .

Use the setBackgroundColorRes(colorRes) or setBackgroundColor(colorInt) to set a color of the fading background.

Simply add margins between images using the withImagesMargin(context, dimenRes) method for dimensions, or use the withImageMarginPixels(int) for pixels size.

Overlay image hides part of the images? Set container padding with dimens using withContainerPadding(context, start, top, end, bottom) or withContainerPadding(context, dimen) for all of the sides evenly. For setting a padding in pixels, just use the withContainerPadding(. ) methods variant.

Status bar visibility

Control the status bar visibility of the opened viewer by using the withHiddenStatusBar(boolean) method ( true by default)

If you need to disable some of the gestures — you can use the allowSwipeToDismiss(boolean) and allowZooming(boolean) methods accordingly.

Here is the example with all of the existing options applied:

Also, you can take a look at the sample project for more information.

Usage with Fresco

If you use the Fresco library — check out the FrescoImageViewer which was also developed by our team.

About

A simple and customizable Android full-screen image viewer with shared image transition support, «pinch to zoom» and «swipe to dismiss» gestures

Источник

Оцените статью