我想为我的 ionic 内容设置背景图片。
我想添加它使用
background-image: url('../assets/imgs/my_image.jpg')
在 CSS 中,但我希望使用 cordova-plugin-camera 从用户上传图像。如您所知,使用该插件我可以用相机拍照或从图库上传照片,我什至可以在 HTML 中显示它,但我不知道如何使用该图像设置背景。
我试过了
.content
{
background-image: {{ myItem.photo }};
}
但是显然不行。
谁能解决这个问题? 提前致谢
这是我上传图片的方式:
HTML:
<button ion-button (click)="presentActionSheet()">
Choose photo
</button>
TS:
public presentActionSheet()
{
let actionSheet = this.actionSheetCtrl.create({
buttons: [
{
text: 'Load from gallery',
handler: () =>
{
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Take picture',
handler: () =>
{
this.takePicture(this.camera.PictureSourceType.CAMERA);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
actionSheet.present();
}
public takePicture(sourceType)
{
// Create options for the Camera Dialog
var options = {
quality: 60,
sourceType: sourceType,
targetHeight: 500,
targetWidth: 500,
mediaType: this.camera.MediaType.PICTURE,
encodingType: this.camera.EncodingType.JPEG,
saveToPhotoAlbum: false,
allowEdit: true
};
// Get the data of an image
this.camera.getPicture(options).then((imagePath) =>
{
// Special handling for Android library
if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY)
{
this.filePath.resolveNativePath(imagePath).then(filePath =>
{
let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
});
}
else
{
let currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
let correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
}
}, (err) =>
{
this.presentToast('Error');
});
}
// Create a new name for the image
private createFileName()
{
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
return newFileName;
}
// Copy the image to a local folder
private copyFileToLocalDir(namePath, currentName, newFileName)
{
this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success =>
{
this.myItem.photo = newFileName;
}, error =>
{
this.presentToast('Error');
});
}
最佳答案
代替:
.content
{
background-image: {{ myItem.photo }};
}
使用[style.background]
:
<div class="content" [style.background]="'url('+myItem.photo+')'"></div>
TS(组件)
ngOnInit(){
this.myItem.photo ="your first url or empty string";
}
//Here you already set the url
private copyFileToLocalDir(namePath, currentName, newFileName)
{
this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success =>
{
this.myItem.photo = newFileName;
}, error =>
{
this.presentToast('Error');
});
}
关于css - 使用相机插件后设置运行时背景图像 - ionic3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50908034/