使用Titanium Mobile开发iPhone/Android应用(07)- Twitter客户端之照相机
使用照相机
在前一篇我们说了一下iPhone中的几个功能,GPS和地图的表示,这篇我们将说说照相机的使用。能够从已经照好的照片中选择照片,而且选择的方式通过Option Dialog罗列,然后将照片发布到TwitPic。
ImageView的准备
要能够预览选择的照片,我们需要准备表示照片的View。这部分和前一篇中的表示地图部分是一样的。
我们在前一篇中作成的message_window.js中追加一下代码:
var imageView = Titanium.UI.createImageView( { width: 'auto', height: 240, top: 220 });imageView.hide();win.add(imageView);
var sourceSelect = Titanium.UI.createOptionDialog({ options:['照相', '从相册选择', '取消'], cancel:2, title:'添加照片'});sourceSelect.addEventListener('click',function(e){ switch( e.index ) { case 0: startCamera(); break; case 1: selectFromPhotoGallery(); break; }});var photoButton = Ti.UI.createButton( { top: 160, left: 100, width: 80, height: 44, title: 'photo' });photoButton.addEventListener( 'click', function() { sourceSelect.show(); });win.add(photoButton);
function startCamera() { Titanium.Media.showCamera( { success:function(event) { var image = event.media; imageView.image = image; imageView.show(); uploadToTwitPic(image); }, //cancel:function(){}, error:function(error) { if (error.code == Titanium.Media.NO_CAMERA) { alert('没有找到照相机!'); } }, saveToPhotoGallery:true, allowEditing:true, mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO] } );}
function selectFromPhotoGallery() { Ti.Media.openPhotoGallery( { success: function(event) { var image = event.media; imageView.image = image; imageView.show(); uploadToTwitPic(image); }, // error: function(error) { }, // cancel: function() { }, allowEditing: false, mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO] } );}
function uploadToTwitPic(image) { var xhr = Ti.Network.createHTTPClient(); var verifyURL = 'https://api.twitter.com/1/account/verify_credentials.json'; var params = { url:verifyURL, method: 'GET' }; var header = twitterApi.oAuthAdapter.createOAuthHeader(params); xhr.onload = function(){ var res = JSON.parse(this.responseText); textArea.value = ( textArea.value || '' ) + ' ' + res.url; }; //xhr.onerror = function(){ }; xhr.open('POST','http://api.twitpic.com/2/upload.json'); xhr.setRequestHeader('X-Verify-Credentials-Authorization',header); xhr.setRequestHeader('X-Auth-Service-Provider',verifyURL); xhr.send( { key: 'YOUR_TWITPIC_API_KEY', message: textArea.value, media: image } );}