图片保持清晰度不变形填充父元素

本文介绍CSS中object-fit和object-position属性的使用方法,详细解释如何让img和video元素在保持原始比例的同时适应不同容器大小,实现剪切、缩放及位置调整。

场景:div里包裹img,img大小可缩放,但不改变图片清晰度,不变形

object-fit 属性   

对图片进行剪切,保留原始比例

object-fit 属性指定元素的内容应该如何去适应指定容器的高度与宽度。

object-fit 一般用于 img 和 video 标签,一般可以对这些元素进行保留原始比例的剪切、缩放或者直接进行拉伸等。

object-fit: fill|contain|cover|scale-down|none|initial|inherit;

object-position 属性

object-position 属性一般与 object-fit一起使用,用来设置元素的位置。

object-position: position|initial|inherit;

 

import router from '@ohos.router'; @Entry @Component struct AdPage { @State countdown: number = 5; @State currentImage: number = 0; private timer: number = 0; private imageTimer: number = 0; // 四张广告图片 private images: Resource[] = [ $r("app.media.gg7"), $r("app.media.gg7"), $r("app.media.gg8"), $r("app.media.gg9") ]; aboutToAppear() { this.startCountdown(); this.startImageChange(); } aboutToDisappear() { if (this.timer) { clearInterval(this.timer); } if (this.imageTimer) { clearInterval(this.imageTimer); } } startCountdown() { this.timer = setInterval(() => { if (this.countdown > 1) { this.countdown--; } else { clearInterval(this.timer); this.skipAd(); } }, 1000); } startImageChange() { this.imageTimer = setInterval(() => { this.currentImage = (this.currentImage + 1) % this.images.length; }, 1500); } skipAd() { router.replaceUrl({ url: 'pages/MainPage' }); } build() { Column() { // 右上角跳过按钮和倒计时 Row() { Text(`${this.countdown}s`) .fontSize(18) .fontColor("#ffffff") .margin({ right: 10 }) Button("跳过") .width(60) .height(30) .backgroundColor("#995f7699") .fontSize(14) .fontColor(Color.White) .onClick(() => { this.skipAd(); }) } .width("100%") .justifyContent(FlexAlign.End) .padding({ right: 15, top: 10 }) // 全屏广告图片轮播 Image(this.images[this.currentImage]) .width("100%") .height("100%") .objectFit(ImageFit.Fill) // 图片指示器 Row({ space: 10 }) { ForEach(this.images, (item: Resource, index: number) => { Column() { // 指示点 } .width(12) .height(12) .backgroundColor(index === this.currentImage ? "#ffffff" : "#99ffffff") .borderRadius(6) }) } .width("100%") .justifyContent(FlexAlign.Center) .margin({ bottom: 80 }) } .width('100%') .height('100%') } }使图片居中
10-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值