UITableViewCell中得UIImageView的大小固定

UITableViewCell中得UIImageView的大小固定,第1张

通常需要imageView,textLabel,detailTextlabel,而UITableViewCell本身提供了方便的自动布局(当有图片和没图片时,textLabel和detailLabel的位置会左右自动调整). 但是图片的大小却是没有办法固定的(直接设置imageView.frame是无法固定imageView的大小的),那么一般来说解决这个问题的办法有两种:

固定显示图片的大小(包括PlaceHolder)

自定义tableViewCell,添加自定义的imageView,textLabel和detailTextLabel

这两种方式都可以解决这个问题,但是这两种方式其实都挺麻烦的,能否直接固定imageView的大小呢? 方法是有的,只需要重载layoutSubviews即可

#import"MyCell.h"

@implementation MyCell

-(void)layoutSubviews{

UIImage*img =self.imageView.image

self.imageView.image= [UIImageimageNamed:@"017.png"]

[superlayoutSubviews]

self.imageView.image= img

}

@end

我们只要使用MyCell就可以固定imageView的大小了,且大小为017.png的大小(一般来说这种页面都会使用一个017.png来显示默认图片).

原理是在UItableVeiw的layoutSubviews调用时,会根据imageView.image的大小来调整imageView,textLabel,detailTextLabel的位置,在此之前我们先将imageView.image设置为017.png图片,等待重新布局完后再将原本的图片设置回去就可以了

1、 在布局文件中定义imageview,但不为其设置资源。

<LinearLayout

android:orientation="vertical"

android:layout_below="@id/title_bar"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<ImageView

android:id="@+id/topImageview"

android:layout_width="match_parent"

android:layout_height="wrap_content"

/>

</LinearLayout>

2、在activity的初始化代码中,初始化imageview 并设定大小:

public void initTopImageView(View view) {

ImageView imageTopview = (ImageView)view.findViewById(R.id.topImageview)

WindowManager windowManager = mParent.getWindowManager()

Display display = windowManager.getDefaultDisplay()

int imageWidth = display.getWidth()

int imageHeight = 0

BitmapFactory.Options option = new BitmapFactory.Options()

option.inJustDecodeBounds = true

Bitmap myMap = BitmapFactory.decodeStream(getResources().openRawResource(R.raw.landing_hot_product_1))

imageHeight = (imageWidth*myMap.getHeight())/myMap.getWidth()

imageTopview.setScaleType(ImageView.ScaleType.FIT_XY)

imageTopview.setLayoutParams(new LinearLayout.LayoutParams(imageWidth,imageHeight))

imageTopview.setImageResource(R.raw.landing_hot_product_1)

myMap.recycle()

}

在给imageview设置图片资源之前,根据比例关系动态计算图片的宽和高,并设置给imageview.


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/6385116.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-21
下一篇 2023-03-21

发表评论

登录后才能评论

评论列表(0条)

保存