黑莓自定义字段drawBitmap不使用整个空间

时间:2011-12-05 18:19:25

标签: blackberry bitmap

我正在绘制Bitmap作为自定义字段的背景,但它不会在整个字段的区域中绘制位图。我也调整了图像的大小,但它总是在右边和底部留下一些空间。这就是它的样子:

enter image description here

以下是一些绘画代码:

public int getPreferredWidth(){
    return phoneWidth;
}

public int getPreferredHeight(){
    return cellHeight;
}

protected void paint(Graphics g) {
    Bitmap img = Bitmap.getBitmapResource("cell_bg.png");        
    img.scaleInto(new Bitmap(phoneWidth, cellHeight), Bitmap.SCALE_TO_FIT);//or other scaling methods
    g.drawBitmap(0, 0, phoneWidth, cellHeight, img, 0, 0);//draw background
//other steps
}

如果按照以下方式设置Background -

,它可以正常工作
Background bg = BackgroundFactory.createBitmapBackground(Bitmap.getBitmapResource("cell_bg.png"),0,0,Background.REPEAT_SCALE_TO_FIT);
this.setBackground(bg);

但是这样,背景图片不可见onFocus

我在这里做错了什么?

3 个答案:

答案 0 :(得分:1)

创建一个编码图像,然后将此编码图像传递给scaleImage()函数

EncodedImage ei = EncodedImage.getEncodedImageResource("res/helpscreen.png");   
        EncodedImage ei1= scaleImage(ei,Graphics.getScreenWidth(),Graphics.getScreenHeight());  


  public EncodedImage scaleImage(EncodedImage source, int requiredWidth, int requiredHeight) 
    {  
        int currentWidthFixed32 = Fixed32.toFP(source.getWidth());  
        int requiredWidthFixed32 = Fixed32.toFP(requiredWidth);  
        int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);  
        int currentHeightFixed32 = Fixed32.toFP(source.getHeight());  
        int requiredHeightFixed32 = Fixed32.toFP(requiredHeight);  
        int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);  
        return source.scaleImage32(scaleXFixed32, scaleYFixed32);  
    } 

然后得到这个位图

 BitmapField logoBitmap = new BitmapField(ei1.getBitmap());  

答案 1 :(得分:1)

此处的问题是您错误地使用了scaleInto()

试试这样:

Bitmap img = Bitmap.getBitmapResource("cell_bg.png");
Bitmap scaled = new Bitmap(phoneWidth, cellHeight);         
img.scaleInto(scaled, Bitmap.SCALE_TO_FIT);//or other scaling methods
g.drawBitmap(0, 0, phoneWidth, cellHeight, scaled, 0, 0);// here draw the scaled image(You here draw the old one)

scaled位图图片作为输出, NOT 原始图片。

答案 2 :(得分:0)

使用此方法缩放代码中的图像:

  private Bitmap getScaledBitmap(String imageName, int width, int height)
  {
      try { 
          EncodedImage image = EncodedImage.getEncodedImageResource(imageName);
          int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
          int currentHeightFixed32 = Fixed32.toFP(image.getHeight());
          int requiredWidthFixed32 = Fixed32.toFP(width);
          int requiredHeightFixed32 = Fixed32.toFP(height);
          int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
          int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);
          image = image.scaleImage32(scaleXFixed32, scaleYFixed32);
          return image.getBitmap();
      } catch(Exception e) {
          return null; // unable to resize the image
      }    
  }