如何显示图像的左上角50x50而不调整大小,仅显示原始分辨率?

时间:2018-09-29 22:45:16

标签: react-native react-native-android

我正在尝试使用Spritesheet制作动画(不使用外部库)

当前尝试在我的Android屏幕中心显示图像的左上角(50像素乘50像素)

但是,我得到的只是将原始图像调整为50x50。我该怎么做,以便不调整原始图像的大小,而只调整该图像的左上角50x50?

1 个答案:

答案 0 :(得分:0)

您可以使用ImageEditor,它不是外部库,而是由react native提供的模块: 如下面的代码所示,我从左上角裁剪(因为x和y的偏移量为0),并且裁剪了150x150像素,如state.croppedWidth-croppedHeight:

import React, { Component } from "react";
import { View, Image, ImageEditor } from "react-native";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cropedPath: null,
      cropedWidth: 150,
      cropedHeight: 150,
      path:
        "https://blog.addthiscdn.com/wp-content/uploads/2016/03/01125908/200-200-pixels.png"
    };
  }

  componentDidMount() {
    this.crop(this.state.path, this.state.cropedWidth, this.state.cropedHeight);
  }

  crop(path, cropedWidth, cropedHeight) {
    ImageEditor.cropImage(
      path,
      (cropData = {
        offset: { x: 0, y: 0 },
        size: { width: cropedWidth, height: cropedHeight },
        resizeMode: "cover"
      }),
      uri => this.setState({ cropedPath: uri }),
      error => console.log("error", error)
    );
  }

  loadImage(path, width, height) {
    return (
      <Image source={{ uri: path }} style={{ width: width, height: height }} />
    );
  }

  render() {
    return (
      <View>
        {this.loadImage(this.state.path, 200, 200)}
        {this.loadImage(
          this.state.cropedPath,
          this.state.cropedWidth,
          this.state.cropedHeight
        )}
      </View>
    );
  }
}

执行后的屏幕截图:
croped image