なんかできたよー。

Web系Tipsを適当につづるBlog.

ImageView画像読み込み時のローディング、読み込み失敗時のダミー画像表示

完成図

f:id:tuki0918:20130407072726p:plain

処理の流れ

  • imageView の「defaultImage」に透明の画像を設定して、Titanium Mobileのデフォルト画像を表示させないように
  • 画像が読み込まれるまで「Indicator」を表示
  • 読み込みが完了 -> 「読み込んだ画像を表示」
  • 読み込みに失敗 -> 「予め用意していた画像を表示」
  • 「Indicator」を削除
Ti.UI.setBackgroundColor '#fff'

win = Ti.UI.createWindow()

# デフォルト画像
defaultImage = "images/load_error.png"

#画像と同じサイズのView
view = Ti.UI.createView
  width: '88dp'
  height: '88dp'
  backgroundColor: '#efefef'
  borderRadius: 5

# 読み込む画像
imageView = Ti.UI.createImageView
  width: '88dp'
  height: '88dp'
  defaultImage: 'images/transparent.png' # 透明の画像
  image: 'http://iideacraft.com/blog-img/icon_home.png'

# ローディング
imageLoading = Ti.UI.createActivityIndicator()
if Ti.Platform.name is 'iPhone OS'
  imageLoading.style = Ti.UI.iPhone.ActivityIndicatorStyle.DARK
else
  imageLoading.style = Ti.UI.ActivityIndicatorStyle.DARK
imageLoading.show()

# 画像読み込みエラー デフォルト画像を表示
imageView.addEventListener 'error', ->
  imageView.image = defaultImage
  return

# 読み込み完了 ローディングを削除
imageView.addEventListener 'load', ->
  view.remove imageLoading
  return

view.add imageLoading
view.add imageView

win.add view

win.open()

 

Class / Module化

  • width, height, image を引数にとる場合の例
#lib/create_imageview.coffee
class CreateImageView
  constructor: (params)->
    # デフォルト画像
    _defaultImage = "images/load_error.png"

    #画像と同じサイズのView
    @view = Ti.UI.createView
      width: params.width
      height: params.height
      backgroundColor: '#efefef'
      borderRadius: 5

    # 読み込む画像
    _imageView = Ti.UI.createImageView
      width: params.width
      height: params.height
      defaultImage: 'images/transparent.png' # 透明の画像
      image: params.image

    # ローディング
    _imageLoading = Ti.UI.createActivityIndicator()
    if Ti.Platform.name is 'iPhone OS'
      _imageLoading.style = Ti.UI.iPhone.ActivityIndicatorStyle.DARK
    else
      _imageLoading.style = Ti.UI.ActivityIndicatorStyle.DARK
    _imageLoading.show()

    # 画像読み込みエラー デフォルト画像を表示
    _imageView.addEventListener 'error', ->
      _imageView.image = _defaultImage
      return

    # 読み込み完了 ローディングを削除
    _imageView.addEventListener 'load', =>
      @view.remove _imageLoading
      return

    @view.add _imageLoading
    @view.add _imageView
    return @view


module.exports.CreateImageView = CreateImageView

実行例

#app.coffee
$ =
  lib: require '/lib/create_imageview'

Ti.UI.setBackgroundColor '#fff'

win = Ti.UI.createWindow()


image = new $.lib.CreateImageView
  width: '88dp'
  height: '88dp'
  image: 'http://iideacraft.com/blog-img/icon_home.png'


win.add image
win.open()